blob: 7c566317bd6ea35b5bf98a8e10a4c47313ed1cb7 [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
54static bool isPointInRect(const Rect& rect, int32_t x, int32_t y) {
55 // Consider all four sides as "inclusive".
56 return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
57}
58
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070059template <typename T>
60inline static void swap(T& a, T& b) {
61 T temp = a;
62 a = b;
63 b = temp;
64}
65
66static float calculateCommonVector(float a, float b) {
67 if (a > 0 && b > 0) {
68 return a < b ? a : b;
69 } else if (a < 0 && b < 0) {
70 return a > b ? a : b;
71 } else {
72 return 0;
73 }
74}
75
76inline static float distance(float x1, float y1, float x2, float y2) {
77 return hypotf(x1 - x2, y1 - y2);
78}
79
80inline static int32_t signExtendNybble(int32_t value) {
81 return value >= 8 ? value - 16 : value;
82}
83
Prabir Pradhan2d613f42022-11-10 20:22:06 +000084static std::tuple<ui::Size /*displayBounds*/, Rect /*physicalFrame*/> getNaturalDisplayInfo(
Prabir Pradhanea31d4f2022-11-10 20:48:01 +000085 const DisplayViewport& viewport) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000086 ui::Size rotatedDisplaySize{viewport.deviceWidth, viewport.deviceHeight};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +000087 if (viewport.orientation == ui::ROTATION_90 || viewport.orientation == ui::ROTATION_270) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000088 std::swap(rotatedDisplaySize.width, rotatedDisplaySize.height);
89 }
90
Prabir Pradhanea31d4f2022-11-10 20:48:01 +000091 ui::Transform rotate(ui::Transform::toRotationFlags(viewport.orientation),
Michael Wrighta9cf4192022-12-01 23:46:39 +000092 rotatedDisplaySize.width, rotatedDisplaySize.height);
Prabir Pradhan2d613f42022-11-10 20:22:06 +000093
94 Rect physicalFrame{viewport.physicalLeft, viewport.physicalTop, viewport.physicalRight,
95 viewport.physicalBottom};
96 physicalFrame = rotate.transform(physicalFrame);
97
98 LOG_ALWAYS_FATAL_IF(!physicalFrame.isValid());
99 if (physicalFrame.isEmpty()) {
100 ALOGE("Viewport is not set properly: %s", viewport.toString().c_str());
101 physicalFrame.right =
102 physicalFrame.left + (physicalFrame.width() == 0 ? 1 : physicalFrame.width());
103 physicalFrame.bottom =
104 physicalFrame.top + (physicalFrame.height() == 0 ? 1 : physicalFrame.height());
105 }
106 return {rotatedDisplaySize, physicalFrame};
107}
108
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700109// --- RawPointerData ---
110
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700111void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
112 float x = 0, y = 0;
113 uint32_t count = touchingIdBits.count();
114 if (count) {
115 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
116 uint32_t id = idBits.clearFirstMarkedBit();
117 const Pointer& pointer = pointerForId(id);
118 x += pointer.x;
119 y += pointer.y;
120 }
121 x /= count;
122 y /= count;
123 }
124 *outX = x;
125 *outY = y;
126}
127
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700128// --- TouchInputMapper ---
129
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800130TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
131 : InputMapper(deviceContext),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000132 mTouchButtonAccumulator(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700133 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100134 mDeviceMode(DeviceMode::DISABLED),
Michael Wrighta9cf4192022-12-01 23:46:39 +0000135 mInputDeviceOrientation(ui::ROTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700136
137TouchInputMapper::~TouchInputMapper() {}
138
Philip Junker4af3b3d2021-12-14 10:36:55 +0100139uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700140 return mSource;
141}
142
143void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
144 InputMapper::populateDeviceInfo(info);
145
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000146 if (mDeviceMode == DeviceMode::DISABLED) {
147 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700148 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000149
150 info->addMotionRange(mOrientedRanges.x);
151 info->addMotionRange(mOrientedRanges.y);
152 info->addMotionRange(mOrientedRanges.pressure);
153
154 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
155 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
156 //
157 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
158 // motion, i.e. the hardware dimensions, as the finger could move completely across the
159 // touchpad in one sample cycle.
160 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
161 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
162 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
163 x.resolution);
164 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
165 y.resolution);
166 }
167
168 if (mOrientedRanges.size) {
169 info->addMotionRange(*mOrientedRanges.size);
170 }
171
172 if (mOrientedRanges.touchMajor) {
173 info->addMotionRange(*mOrientedRanges.touchMajor);
174 info->addMotionRange(*mOrientedRanges.touchMinor);
175 }
176
177 if (mOrientedRanges.toolMajor) {
178 info->addMotionRange(*mOrientedRanges.toolMajor);
179 info->addMotionRange(*mOrientedRanges.toolMinor);
180 }
181
182 if (mOrientedRanges.orientation) {
183 info->addMotionRange(*mOrientedRanges.orientation);
184 }
185
186 if (mOrientedRanges.distance) {
187 info->addMotionRange(*mOrientedRanges.distance);
188 }
189
190 if (mOrientedRanges.tilt) {
191 info->addMotionRange(*mOrientedRanges.tilt);
192 }
193
194 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
195 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
196 }
197 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
198 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
199 }
200 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
201 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
202 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
203 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat, x.fuzz,
204 x.resolution);
205 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat, y.fuzz,
206 y.resolution);
207 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat, x.fuzz,
208 x.resolution);
209 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat, y.fuzz,
210 y.resolution);
211 }
212 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000213 info->setSupportsUsi(mParameters.supportsUsi);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700214}
215
216void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700217 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800218 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700219 dumpParameters(dump);
220 dumpVirtualKeys(dump);
221 dumpRawPointerAxes(dump);
222 dumpCalibration(dump);
223 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700224 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700225
226 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000227 mRawToDisplay.dump(dump, "RawToDisplay Transform:", INDENT4);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700228 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
229 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
230 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
231 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
232 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
233 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
234 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
235 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
236 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
237 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
238 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
239 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
240 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
241 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
242
243 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
244 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
245 mLastRawState.rawPointerData.pointerCount);
246 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
247 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
248 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
249 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
250 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
251 "toolType=%d, isHovering=%s\n",
252 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
253 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
254 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
255 pointer.distance, pointer.toolType, toString(pointer.isHovering));
256 }
257
258 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
259 mLastCookedState.buttonState);
260 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
261 mLastCookedState.cookedPointerData.pointerCount);
262 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
263 const PointerProperties& pointerProperties =
264 mLastCookedState.cookedPointerData.pointerProperties[i];
265 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000266 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
267 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
268 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700269 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
270 "toolType=%d, isHovering=%s\n",
271 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000272 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
273 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700274 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
275 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
276 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
277 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
278 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
279 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
280 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
281 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
282 pointerProperties.toolType,
283 toString(mLastCookedState.cookedPointerData.isHovering(i)));
284 }
285
286 dump += INDENT3 "Stylus Fusion:\n";
287 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
288 toString(mExternalStylusConnected));
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000289 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
290 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700291 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
292 mExternalStylusFusionTimeout);
Prabir Pradhan124ea442022-10-28 20:27:44 +0000293 dump += StringPrintf(INDENT4 " External Stylus Buttons Applied: 0x%08x",
294 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700295 dump += INDENT3 "External Stylus State:\n";
296 dumpStylusState(dump, mExternalStylusState);
297
Michael Wright227c5542020-07-02 18:30:52 +0100298 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700299 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
300 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
301 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
302 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
303 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
304 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
305 }
306}
307
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700308std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
309 const InputReaderConfiguration* config,
310 uint32_t changes) {
311 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700312
313 mConfig = *config;
314
315 if (!changes) { // first time only
316 // Configure basic parameters.
317 configureParameters();
318
319 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800320 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000321 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700322
323 // Configure absolute axis information.
324 configureRawPointerAxes();
325
326 // Prepare input device calibration.
327 parseCalibration();
328 resolveCalibration();
329 }
330
331 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
332 // Update location calibration to reflect current settings
333 updateAffineTransformation();
334 }
335
336 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
337 // Update pointer speed.
338 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
339 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
340 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
341 }
342
343 bool resetNeeded = false;
344 if (!changes ||
345 (changes &
346 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800347 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700348 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
349 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
350 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700351 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700352 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700353 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700354 }
355
356 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700357 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000358
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700359 // Send reset, unless this is the first time the device has been configured,
360 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000361 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700362 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700363 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700364}
365
366void TouchInputMapper::resolveExternalStylusPresence() {
367 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800368 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700369 mExternalStylusConnected = !devices.empty();
370
371 if (!mExternalStylusConnected) {
372 resetExternalStylus();
373 }
374}
375
376void TouchInputMapper::configureParameters() {
377 // Use the pointer presentation mode for devices that do not support distinct
378 // multitouch. The spot-based presentation relies on being able to accurately
379 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800380 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100381 ? Parameters::GestureMode::SINGLE_TOUCH
382 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700383
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700384 std::string gestureModeString;
385 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800386 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700387 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100388 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700389 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100390 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700391 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700392 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700393 }
394 }
395
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000396 configureDeviceType();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700397
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800398 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700399
Michael Wright227c5542020-07-02 18:30:52 +0100400 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700401 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800402 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700403
Michael Wrighta9cf4192022-12-01 23:46:39 +0000404 mParameters.orientation = ui::ROTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700405 std::string orientationString;
406 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700407 orientationString)) {
408 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
409 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
410 } else if (orientationString == "ORIENTATION_90") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000411 mParameters.orientation = ui::ROTATION_90;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700412 } else if (orientationString == "ORIENTATION_180") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000413 mParameters.orientation = ui::ROTATION_180;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700414 } else if (orientationString == "ORIENTATION_270") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000415 mParameters.orientation = ui::ROTATION_270;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700416 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700417 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700418 }
419 }
420
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700421 mParameters.hasAssociatedDisplay = false;
422 mParameters.associatedDisplayIsExternal = false;
423 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100424 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000425 mParameters.deviceType == Parameters::DeviceType::POINTER ||
426 (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
427 getDeviceContext().getAssociatedViewport())) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700428 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100429 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800430 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700431 std::string uniqueDisplayId;
432 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800433 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700434 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
435 }
436 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800437 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700438 mParameters.hasAssociatedDisplay = true;
439 }
440
441 // Initial downs on external touch devices should wake the device.
442 // Normally we don't do this for internal touch screens to prevent them from waking
443 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800444 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700445 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000446
447 mParameters.supportsUsi = false;
448 getDeviceContext().getConfiguration().tryGetProperty("touch.supportsUsi",
449 mParameters.supportsUsi);
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700450
451 mParameters.enableForInactiveViewport = false;
452 getDeviceContext().getConfiguration().tryGetProperty("touch.enableForInactiveViewport",
453 mParameters.enableForInactiveViewport);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700454}
455
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000456void TouchInputMapper::configureDeviceType() {
457 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
458 // The device is a touch screen.
459 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
460 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
461 // The device is a pointing device like a track pad.
462 mParameters.deviceType = Parameters::DeviceType::POINTER;
463 } else {
464 // The device is a touch pad of unknown purpose.
465 mParameters.deviceType = Parameters::DeviceType::POINTER;
466 }
467
468 // Type association takes precedence over the device type found in the idc file.
469 std::string deviceTypeString = getDeviceContext().getDeviceTypeAssociation().value_or("");
470 if (deviceTypeString.empty()) {
471 getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType", deviceTypeString);
472 }
473 if (deviceTypeString == "touchScreen") {
474 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
475 } else if (deviceTypeString == "touchNavigation") {
476 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
477 } else if (deviceTypeString == "pointer") {
478 mParameters.deviceType = Parameters::DeviceType::POINTER;
479 } else if (deviceTypeString != "default" && deviceTypeString != "") {
480 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
481 }
482}
483
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700484void TouchInputMapper::dumpParameters(std::string& dump) {
485 dump += INDENT3 "Parameters:\n";
486
Dominik Laskowski75788452021-02-09 18:51:25 -0800487 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700488
Dominik Laskowski75788452021-02-09 18:51:25 -0800489 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700490
491 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
492 "displayId='%s'\n",
493 toString(mParameters.hasAssociatedDisplay),
494 toString(mParameters.associatedDisplayIsExternal),
495 mParameters.uniqueDisplayId.c_str());
496 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800497 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhan167c2702022-09-14 00:37:24 +0000498 dump += StringPrintf(INDENT4 "SupportsUsi: %s\n", toString(mParameters.supportsUsi));
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700499 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
500 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700501}
502
503void TouchInputMapper::configureRawPointerAxes() {
504 mRawPointerAxes.clear();
505}
506
507void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
508 dump += INDENT3 "Raw Touch Axes:\n";
509 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
510 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
511 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
512 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
513 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
514 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
515 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
516 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
517 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
518 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
519 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
520 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
521 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
522}
523
524bool TouchInputMapper::hasExternalStylus() const {
525 return mExternalStylusConnected;
526}
527
528/**
529 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000530 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800531 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000532 * 3. Get the matching viewport by either unique id in idc file or by the display type
533 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800534 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700535 */
536std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800537 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000538 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800539 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700540 }
541
Christine Franks2a2293c2022-01-18 11:51:16 -0800542 const std::optional<std::string> associatedDisplayUniqueId =
543 getDeviceContext().getAssociatedDisplayUniqueId();
544 if (associatedDisplayUniqueId) {
545 return getDeviceContext().getAssociatedViewport();
546 }
547
Michael Wright227c5542020-07-02 18:30:52 +0100548 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800549 std::optional<DisplayViewport> viewport =
550 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
551 if (viewport) {
552 return viewport;
553 } else {
554 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
555 mConfig.defaultPointerDisplayId);
556 }
557 }
558
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700559 // Check if uniqueDisplayId is specified in idc file.
560 if (!mParameters.uniqueDisplayId.empty()) {
561 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
562 }
563
564 ViewportType viewportTypeToUse;
565 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100566 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700567 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100568 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700569 }
570
571 std::optional<DisplayViewport> viewport =
572 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100573 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700574 ALOGW("Input device %s should be associated with external display, "
575 "fallback to internal one for the external viewport is not found.",
576 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100577 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700578 }
579
580 return viewport;
581 }
582
583 // No associated display, return a non-display viewport.
584 DisplayViewport newViewport;
585 // Raw width and height in the natural orientation.
586 int32_t rawWidth = mRawPointerAxes.getRawWidth();
587 int32_t rawHeight = mRawPointerAxes.getRawHeight();
588 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
589 return std::make_optional(newViewport);
590}
591
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800592int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
593 if (resolution < 0) {
594 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
595 getDeviceName().c_str());
596 return 0;
597 }
598 return resolution;
599}
600
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800601void TouchInputMapper::initializeSizeRanges() {
602 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
603 mSizeScale = 0.0f;
604 return;
605 }
606
607 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000608 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800609
610 // Size factors.
611 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
612 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
613 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
614 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
615 } else {
616 mSizeScale = 0.0f;
617 }
618
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700619 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
620 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
621 .source = mSource,
622 .min = 0,
623 .max = diagonalSize,
624 .flat = 0,
625 .fuzz = 0,
626 .resolution = 0,
627 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800628
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800629 if (mRawPointerAxes.touchMajor.valid) {
630 mRawPointerAxes.touchMajor.resolution =
631 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700632 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800633 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800634
635 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700636 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800637 if (mRawPointerAxes.touchMinor.valid) {
638 mRawPointerAxes.touchMinor.resolution =
639 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700640 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800641 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800642
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700643 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
644 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
645 .source = mSource,
646 .min = 0,
647 .max = diagonalSize,
648 .flat = 0,
649 .fuzz = 0,
650 .resolution = 0,
651 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800652 if (mRawPointerAxes.toolMajor.valid) {
653 mRawPointerAxes.toolMajor.resolution =
654 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700655 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800656 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800657
658 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700659 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800660 if (mRawPointerAxes.toolMinor.valid) {
661 mRawPointerAxes.toolMinor.resolution =
662 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700663 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800664 }
665
666 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700667 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
668 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
669 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
670 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800671 } else {
672 // Support for other calibrations can be added here.
673 ALOGW("%s calibration is not supported for size ranges at the moment. "
674 "Using raw resolution instead",
675 ftl::enum_string(mCalibration.sizeCalibration).c_str());
676 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800677
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700678 mOrientedRanges.size = InputDeviceInfo::MotionRange{
679 .axis = AMOTION_EVENT_AXIS_SIZE,
680 .source = mSource,
681 .min = 0,
682 .max = 1.0,
683 .flat = 0,
684 .fuzz = 0,
685 .resolution = 0,
686 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800687}
688
689void TouchInputMapper::initializeOrientedRanges() {
690 // Configure X and Y factors.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000691 mXScale = float(mDisplayBounds.width) / mRawPointerAxes.getRawWidth();
692 mYScale = float(mDisplayBounds.height) / mRawPointerAxes.getRawHeight();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800693 mXPrecision = 1.0f / mXScale;
694 mYPrecision = 1.0f / mYScale;
695
696 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
697 mOrientedRanges.x.source = mSource;
698 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
699 mOrientedRanges.y.source = mSource;
700
701 // Scale factor for terms that are not oriented in a particular axis.
702 // If the pixels are square then xScale == yScale otherwise we fake it
703 // by choosing an average.
704 mGeometricScale = avg(mXScale, mYScale);
705
706 initializeSizeRanges();
707
708 // Pressure factors.
709 mPressureScale = 0;
710 float pressureMax = 1.0;
711 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
712 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700713 if (mCalibration.pressureScale) {
714 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800715 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
716 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
717 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
718 }
719 }
720
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700721 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
722 .axis = AMOTION_EVENT_AXIS_PRESSURE,
723 .source = mSource,
724 .min = 0,
725 .max = pressureMax,
726 .flat = 0,
727 .fuzz = 0,
728 .resolution = 0,
729 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800730
731 // Tilt
732 mTiltXCenter = 0;
733 mTiltXScale = 0;
734 mTiltYCenter = 0;
735 mTiltYScale = 0;
736 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
737 if (mHaveTilt) {
738 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
739 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
740 mTiltXScale = M_PI / 180;
741 mTiltYScale = M_PI / 180;
742
743 if (mRawPointerAxes.tiltX.resolution) {
744 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
745 }
746 if (mRawPointerAxes.tiltY.resolution) {
747 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
748 }
749
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700750 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
751 .axis = AMOTION_EVENT_AXIS_TILT,
752 .source = mSource,
753 .min = 0,
754 .max = M_PI_2,
755 .flat = 0,
756 .fuzz = 0,
757 .resolution = 0,
758 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800759 }
760
761 // Orientation
762 mOrientationScale = 0;
763 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700764 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
765 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
766 .source = mSource,
767 .min = -M_PI,
768 .max = M_PI,
769 .flat = 0,
770 .fuzz = 0,
771 .resolution = 0,
772 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800773
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800774 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
775 if (mCalibration.orientationCalibration ==
776 Calibration::OrientationCalibration::INTERPOLATED) {
777 if (mRawPointerAxes.orientation.valid) {
778 if (mRawPointerAxes.orientation.maxValue > 0) {
779 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
780 } else if (mRawPointerAxes.orientation.minValue < 0) {
781 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
782 } else {
783 mOrientationScale = 0;
784 }
785 }
786 }
787
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700788 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
789 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
790 .source = mSource,
791 .min = -M_PI_2,
792 .max = M_PI_2,
793 .flat = 0,
794 .fuzz = 0,
795 .resolution = 0,
796 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800797 }
798
799 // Distance
800 mDistanceScale = 0;
801 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
802 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700803 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800804 }
805
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700806 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800807
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700808 .axis = AMOTION_EVENT_AXIS_DISTANCE,
809 .source = mSource,
810 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
811 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
812 .flat = 0,
813 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
814 .resolution = 0,
815 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800816 }
817
818 // Compute oriented precision, scales and ranges.
819 // Note that the maximum value reported is an inclusive maximum value so it is one
820 // unit less than the total width or height of the display.
821 switch (mInputDeviceOrientation) {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000822 case ui::ROTATION_90:
823 case ui::ROTATION_270:
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800824 mOrientedXPrecision = mYPrecision;
825 mOrientedYPrecision = mXPrecision;
826
827 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000828 mOrientedRanges.x.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800829 mOrientedRanges.x.flat = 0;
830 mOrientedRanges.x.fuzz = 0;
831 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
832
833 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000834 mOrientedRanges.y.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800835 mOrientedRanges.y.flat = 0;
836 mOrientedRanges.y.fuzz = 0;
837 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
838 break;
839
840 default:
841 mOrientedXPrecision = mXPrecision;
842 mOrientedYPrecision = mYPrecision;
843
844 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000845 mOrientedRanges.x.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800846 mOrientedRanges.x.flat = 0;
847 mOrientedRanges.x.fuzz = 0;
848 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
849
850 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000851 mOrientedRanges.y.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800852 mOrientedRanges.y.flat = 0;
853 mOrientedRanges.y.fuzz = 0;
854 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
855 break;
856 }
857}
858
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000859ui::Transform TouchInputMapper::computeInputTransform() const {
860 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
861
862 ui::Size rotatedRawSize = rawSize;
863 if (mInputDeviceOrientation == ui::ROTATION_270 || mInputDeviceOrientation == ui::ROTATION_90) {
864 std::swap(rotatedRawSize.width, rotatedRawSize.height);
865 }
866
867 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
868 ui::Transform undoRawOffset;
869 undoRawOffset.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
870
871 // Step 2: Rotate the raw coordinates to the expected orientation.
872 ui::Transform rotate;
873 // When rotating raw coordinates, the raw size will be used as an offset.
874 // Account for the extra unit added to the raw range when the raw size was calculated.
875 rotate.set(ui::Transform::toRotationFlags(-mInputDeviceOrientation), rotatedRawSize.width - 1,
876 rotatedRawSize.height - 1);
877
878 // Step 3: Scale the raw coordinates to the display space.
879 ui::Transform scaleToDisplay;
880 const float xScale = static_cast<float>(mDisplayBounds.width) / rotatedRawSize.width;
881 const float yScale = static_cast<float>(mDisplayBounds.height) / rotatedRawSize.height;
882 scaleToDisplay.set(xScale, 0, 0, yScale);
883
884 return (scaleToDisplay * (rotate * undoRawOffset));
885}
886
Prabir Pradhan1728b212021-10-19 16:00:03 -0700887void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000888 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700889
890 resolveExternalStylusPresence();
891
892 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100893 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000894 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700895 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100896 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700897 if (hasStylus()) {
898 mSource |= AINPUT_SOURCE_STYLUS;
Harry Cutts16a24cc2022-10-26 15:22:19 +0000899 } else {
900 mSource |= AINPUT_SOURCE_TOUCHPAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700901 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800902 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700903 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100904 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700905 if (hasStylus()) {
906 mSource |= AINPUT_SOURCE_STYLUS;
907 }
908 if (hasExternalStylus()) {
909 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
910 }
Michael Wright227c5542020-07-02 18:30:52 +0100911 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700912 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100913 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700914 } else {
915 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100916 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700917 }
918
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000919 const std::optional<DisplayViewport> newViewportOpt = findViewport();
920
921 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700922 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
923 ALOGW("Touch device '%s' did not report support for X or Y axis! "
924 "The device will be inoperable.",
925 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100926 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000927 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700928 ALOGI("Touch device '%s' could not query the properties of its associated "
929 "display. The device will be inoperable until the display size "
930 "becomes available.",
931 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100932 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700933 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000934 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
935 getDeviceName().c_str(), getDeviceId());
936 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000937 }
938
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700939 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000940 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000941 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
942 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
943 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
944 const float rawMeanResolution =
945 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700946
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000947 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
948 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700949 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700950 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000951 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
952 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
953 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700954
Michael Wright227c5542020-07-02 18:30:52 +0100955 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000956 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700957
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000958 std::tie(mDisplayBounds, mPhysicalFrameInDisplay) = getNaturalDisplayInfo(mViewport);
Prabir Pradhan5632d622021-09-06 07:57:20 -0700959
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000960 // InputReader works in the un-rotated display coordinate space, so we don't need to do
961 // anything if the device is already orientation-aware. If the device is not
962 // orientation-aware, then we need to apply the inverse rotation of the display so that
963 // when the display rotation is applied later as a part of the per-window transform, we
964 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700965 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +0000966 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000967 : getInverseRotation(mViewport.orientation);
968 // For orientation-aware devices that work in the un-rotated coordinate space, the
969 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000970 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000971 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700972
973 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +0000974 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000975 mRawToDisplay = computeInputTransform();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700976 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000977 mDisplayBounds = rawSize;
978 mPhysicalFrameInDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +0000979 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000980 mRawToDisplay.reset();
981 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700982 }
983 }
984
985 // If moving between pointer modes, need to reset some state.
986 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
987 if (deviceModeChanged) {
988 mOrientedRanges.clear();
989 }
990
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800991 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
992 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100993 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800994 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000995 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
996 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800997 if (mPointerController == nullptr) {
998 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700999 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001000 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001001 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1002 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001003 } else {
lilinnandef700b2022-06-17 19:32:01 +08001004 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1005 !mConfig.showTouches) {
1006 mPointerController->clearSpots();
1007 }
Michael Wright17db18e2020-06-26 20:51:44 +01001008 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001009 }
1010
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001011 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001012 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001013 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001014 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001015 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001016
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001017 configureVirtualKeys();
1018
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001019 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001020
1021 // Location
1022 updateAffineTransformation();
1023
Michael Wright227c5542020-07-02 18:30:52 +01001024 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001025 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001026 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1027 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001028
1029 // Scale movements such that one whole swipe of the touch pad covers a
1030 // given area relative to the diagonal size of the display when no acceleration
1031 // is applied.
1032 // Assume that the touch pad has a square aspect ratio such that movements in
1033 // X and Y of the same number of raw units cover the same physical distance.
1034 mPointerXMovementScale =
1035 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1036 mPointerYMovementScale = mPointerXMovementScale;
1037
1038 // Scale zooms to cover a smaller range of the display than movements do.
1039 // This value determines the area around the pointer that is affected by freeform
1040 // pointer gestures.
1041 mPointerXZoomScale =
1042 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1043 mPointerYZoomScale = mPointerXZoomScale;
1044
HQ Liue6983c72022-04-19 22:14:56 +00001045 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1046 // axis is non positive value.
1047 const float minFreeformGestureWidth =
1048 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1049
1050 mPointerGestureMaxSwipeWidth =
1051 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1052 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001053 }
1054
1055 // Inform the dispatcher about the changes.
1056 *outResetNeeded = true;
1057 bumpGeneration();
1058 }
1059}
1060
Prabir Pradhan1728b212021-10-19 16:00:03 -07001061void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001062 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001063 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
1064 dump += StringPrintf(INDENT3 "PhysicalFrame: %s\n", toString(mPhysicalFrameInDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001065 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001066}
1067
1068void TouchInputMapper::configureVirtualKeys() {
1069 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001070 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001071
1072 mVirtualKeys.clear();
1073
1074 if (virtualKeyDefinitions.size() == 0) {
1075 return;
1076 }
1077
1078 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1079 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1080 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1081 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1082
1083 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1084 VirtualKey virtualKey;
1085
1086 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1087 int32_t keyCode;
1088 int32_t dummyKeyMetaState;
1089 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001090 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1091 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001092 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1093 continue; // drop the key
1094 }
1095
1096 virtualKey.keyCode = keyCode;
1097 virtualKey.flags = flags;
1098
1099 // convert the key definition's display coordinates into touch coordinates for a hit box
1100 int32_t halfWidth = virtualKeyDefinition.width / 2;
1101 int32_t halfHeight = virtualKeyDefinition.height / 2;
1102
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001103 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1104 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001105 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001106 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1107 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001108 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001109 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1110 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001111 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001112 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1113 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001114 touchScreenTop;
1115 mVirtualKeys.push_back(virtualKey);
1116 }
1117}
1118
1119void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1120 if (!mVirtualKeys.empty()) {
1121 dump += INDENT3 "Virtual Keys:\n";
1122
1123 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1124 const VirtualKey& virtualKey = mVirtualKeys[i];
1125 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1126 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1127 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1128 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1129 }
1130 }
1131}
1132
1133void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001134 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001135 Calibration& out = mCalibration;
1136
1137 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001138 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001139 std::string sizeCalibrationString;
1140 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001141 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001142 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001143 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001144 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001146 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001148 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001149 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001150 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001151 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001152 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001153 }
1154 }
1155
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001156 float sizeScale;
1157
1158 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1159 out.sizeScale = sizeScale;
1160 }
1161 float sizeBias;
1162 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1163 out.sizeBias = sizeBias;
1164 }
1165 bool sizeIsSummed;
1166 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1167 out.sizeIsSummed = sizeIsSummed;
1168 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001169
1170 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001172 std::string pressureCalibrationString;
1173 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001175 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001177 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001178 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001179 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001180 } else if (pressureCalibrationString != "default") {
1181 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001182 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001183 }
1184 }
1185
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001186 float pressureScale;
1187 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1188 out.pressureScale = pressureScale;
1189 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001190
1191 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001192 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001193 std::string orientationCalibrationString;
1194 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001195 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001196 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001197 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001198 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001199 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001201 } else if (orientationCalibrationString != "default") {
1202 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001203 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001204 }
1205 }
1206
1207 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001208 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001209 std::string distanceCalibrationString;
1210 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001212 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001213 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001214 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001215 } else if (distanceCalibrationString != "default") {
1216 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001217 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001218 }
1219 }
1220
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001221 float distanceScale;
1222 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1223 out.distanceScale = distanceScale;
1224 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001225
Michael Wright227c5542020-07-02 18:30:52 +01001226 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001227 std::string coverageCalibrationString;
1228 if (in.tryGetProperty("touch.coverage.calibration", coverageCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001230 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001231 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001232 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001233 } else if (coverageCalibrationString != "default") {
1234 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001235 coverageCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001236 }
1237 }
1238}
1239
1240void TouchInputMapper::resolveCalibration() {
1241 // Size
1242 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001243 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1244 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001245 }
1246 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001247 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248 }
1249
1250 // Pressure
1251 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001252 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1253 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001254 }
1255 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001256 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001257 }
1258
1259 // Orientation
1260 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001261 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1262 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001263 }
1264 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001265 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001266 }
1267
1268 // Distance
1269 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001270 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1271 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001272 }
1273 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001274 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001275 }
1276
1277 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001278 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1279 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001280 }
1281}
1282
1283void TouchInputMapper::dumpCalibration(std::string& dump) {
1284 dump += INDENT3 "Calibration:\n";
1285
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001286 dump += INDENT4 "touch.size.calibration: ";
1287 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001288
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001289 if (mCalibration.sizeScale) {
1290 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001291 }
1292
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001293 if (mCalibration.sizeBias) {
1294 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001295 }
1296
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001297 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001299 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001300 }
1301
1302 // Pressure
1303 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001304 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001305 dump += INDENT4 "touch.pressure.calibration: none\n";
1306 break;
Michael Wright227c5542020-07-02 18:30:52 +01001307 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001308 dump += INDENT4 "touch.pressure.calibration: physical\n";
1309 break;
Michael Wright227c5542020-07-02 18:30:52 +01001310 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001311 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1312 break;
1313 default:
1314 ALOG_ASSERT(false);
1315 }
1316
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001317 if (mCalibration.pressureScale) {
1318 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001319 }
1320
1321 // Orientation
1322 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001323 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001324 dump += INDENT4 "touch.orientation.calibration: none\n";
1325 break;
Michael Wright227c5542020-07-02 18:30:52 +01001326 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001327 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1328 break;
Michael Wright227c5542020-07-02 18:30:52 +01001329 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001330 dump += INDENT4 "touch.orientation.calibration: vector\n";
1331 break;
1332 default:
1333 ALOG_ASSERT(false);
1334 }
1335
1336 // Distance
1337 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001338 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001339 dump += INDENT4 "touch.distance.calibration: none\n";
1340 break;
Michael Wright227c5542020-07-02 18:30:52 +01001341 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001342 dump += INDENT4 "touch.distance.calibration: scaled\n";
1343 break;
1344 default:
1345 ALOG_ASSERT(false);
1346 }
1347
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001348 if (mCalibration.distanceScale) {
1349 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001350 }
1351
1352 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001353 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001354 dump += INDENT4 "touch.coverage.calibration: none\n";
1355 break;
Michael Wright227c5542020-07-02 18:30:52 +01001356 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001357 dump += INDENT4 "touch.coverage.calibration: box\n";
1358 break;
1359 default:
1360 ALOG_ASSERT(false);
1361 }
1362}
1363
1364void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1365 dump += INDENT3 "Affine Transformation:\n";
1366
1367 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1368 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1369 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1370 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1371 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1372 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1373}
1374
1375void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001376 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001377 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001378}
1379
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001380std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001381 std::list<NotifyArgs> out = cancelTouch(when, when);
1382 updateTouchSpots();
1383
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001384 mCursorButtonAccumulator.reset(getDeviceContext());
1385 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001386 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001387
1388 mPointerVelocityControl.reset();
1389 mWheelXVelocityControl.reset();
1390 mWheelYVelocityControl.reset();
1391
1392 mRawStatesPending.clear();
1393 mCurrentRawState.clear();
1394 mCurrentCookedState.clear();
1395 mLastRawState.clear();
1396 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001397 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001398 mSentHoverEnter = false;
1399 mHavePointerIds = false;
1400 mCurrentMotionAborted = false;
1401 mDownTime = 0;
1402
1403 mCurrentVirtualKey.down = false;
1404
1405 mPointerGesture.reset();
1406 mPointerSimple.reset();
1407 resetExternalStylus();
1408
1409 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001410 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001411 mPointerController->clearSpots();
1412 }
1413
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001414 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001415}
1416
1417void TouchInputMapper::resetExternalStylus() {
1418 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001419 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001420 mExternalStylusFusionTimeout = LLONG_MAX;
1421 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001422 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001423}
1424
1425void TouchInputMapper::clearStylusDataPendingFlags() {
1426 mExternalStylusDataPending = false;
1427 mExternalStylusFusionTimeout = LLONG_MAX;
1428}
1429
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001430std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001431 mCursorButtonAccumulator.process(rawEvent);
1432 mCursorScrollAccumulator.process(rawEvent);
1433 mTouchButtonAccumulator.process(rawEvent);
1434
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001435 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001436 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001437 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001438 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001439 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001440}
1441
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001442std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1443 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001444 if (mDeviceMode == DeviceMode::DISABLED) {
1445 // Only save the last pending state when the device is disabled.
1446 mRawStatesPending.clear();
1447 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001448 // Push a new state.
1449 mRawStatesPending.emplace_back();
1450
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001451 RawState& next = mRawStatesPending.back();
1452 next.clear();
1453 next.when = when;
1454 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001455
1456 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001457 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001458 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1459
1460 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001461 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1462 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001463 mCursorScrollAccumulator.finishSync();
1464
1465 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001466 syncTouch(when, &next);
1467
1468 // The last RawState is the actually second to last, since we just added a new state
1469 const RawState& last =
1470 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001471
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001472 std::tie(next.when, next.readTime) =
1473 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1474 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001475
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001476 // Assign pointer ids.
1477 if (!mHavePointerIds) {
1478 assignPointerIds(last, next);
1479 }
1480
Harry Cutts45483602022-08-24 14:36:48 +00001481 ALOGD_IF(DEBUG_RAW_EVENTS,
1482 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1483 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1484 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1485 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1486 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1487 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001488
Arthur Hung9ad18942021-06-19 02:04:46 +00001489 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1490 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1491 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1492 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1493 next.rawPointerData.hoveringIdBits.value);
1494 }
1495
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001496 out += processRawTouches(false /*timeout*/);
1497 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001498}
1499
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001500std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1501 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001502 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001503 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001504 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001505 }
1506
1507 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1508 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1509 // touching the current state will only observe the events that have been dispatched to the
1510 // rest of the pipeline.
1511 const size_t N = mRawStatesPending.size();
1512 size_t count;
1513 for (count = 0; count < N; count++) {
1514 const RawState& next = mRawStatesPending[count];
1515
1516 // A failure to assign the stylus id means that we're waiting on stylus data
1517 // and so should defer the rest of the pipeline.
1518 if (assignExternalStylusId(next, timeout)) {
1519 break;
1520 }
1521
1522 // All ready to go.
1523 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001524 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001525 if (mCurrentRawState.when < mLastRawState.when) {
1526 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001527 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001528 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001529 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001530 }
1531 if (count != 0) {
1532 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1533 }
1534
1535 if (mExternalStylusDataPending) {
1536 if (timeout) {
1537 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1538 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001539 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001540 ALOGD_IF(DEBUG_STYLUS_FUSION,
1541 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001542 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001543 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001544 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1545 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1546 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1547 }
1548 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001549 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001550}
1551
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001552std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1553 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001554 // Always start with a clean state.
1555 mCurrentCookedState.clear();
1556
1557 // Apply stylus buttons to current raw state.
1558 applyExternalStylusButtonState(when);
1559
1560 // Handle policy on initial down or hover events.
1561 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1562 mCurrentRawState.rawPointerData.pointerCount != 0;
1563
1564 uint32_t policyFlags = 0;
1565 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1566 if (initialDown || buttonsPressed) {
1567 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001568 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001569 getContext()->fadePointer();
1570 }
1571
1572 if (mParameters.wake) {
1573 policyFlags |= POLICY_FLAG_WAKE;
1574 }
1575 }
1576
1577 // Consume raw off-screen touches before cooking pointer data.
1578 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001579 bool consumed;
1580 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1581 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001582 mCurrentRawState.rawPointerData.clear();
1583 }
1584
1585 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1586 // with cooked pointer data that has the same ids and indices as the raw data.
1587 // The following code can use either the raw or cooked data, as needed.
1588 cookPointerData();
1589
1590 // Apply stylus pressure to current cooked state.
1591 applyExternalStylusTouchState(when);
1592
1593 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001594 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1595 mSource, mViewport.displayId, policyFlags,
1596 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001597
1598 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001599 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001600 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !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 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1607 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1608 mCurrentCookedState.fingerIdBits.markBit(id);
1609 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1610 mCurrentCookedState.mouseIdBits.markBit(id);
1611 }
1612 }
1613 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1614 uint32_t id = idBits.clearFirstMarkedBit();
1615 const RawPointerData::Pointer& pointer =
1616 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001617 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001618 mCurrentCookedState.stylusIdBits.markBit(id);
1619 }
1620 }
1621
1622 // Stylus takes precedence over all tools, then mouse, then finger.
1623 PointerUsage pointerUsage = mPointerUsage;
1624 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1625 mCurrentCookedState.mouseIdBits.clear();
1626 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001627 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001628 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1629 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001630 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001631 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1632 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001633 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001634 }
1635
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001636 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001637 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001638 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001639 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001640 out += dispatchButtonRelease(when, readTime, policyFlags);
1641 out += dispatchHoverExit(when, readTime, policyFlags);
1642 out += dispatchTouches(when, readTime, policyFlags);
1643 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1644 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001645 }
1646
1647 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1648 mCurrentMotionAborted = false;
1649 }
1650 }
1651
1652 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001653 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1654 mSource, mViewport.displayId, policyFlags,
1655 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001656
1657 // Clear some transient state.
1658 mCurrentRawState.rawVScroll = 0;
1659 mCurrentRawState.rawHScroll = 0;
1660
1661 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001662 mLastRawState = mCurrentRawState;
1663 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001664 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001665}
1666
Garfield Tanc734e4f2021-01-15 20:01:39 -08001667void TouchInputMapper::updateTouchSpots() {
1668 if (!mConfig.showTouches || mPointerController == nullptr) {
1669 return;
1670 }
1671
1672 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1673 // clear touch spots.
1674 if (mDeviceMode != DeviceMode::DIRECT &&
1675 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1676 return;
1677 }
1678
1679 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1680 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1681
1682 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001683 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1684 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001685 mCurrentCookedState.cookedPointerData.touchingIdBits,
1686 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001687}
1688
1689bool TouchInputMapper::isTouchScreen() {
1690 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1691 mParameters.hasAssociatedDisplay;
1692}
1693
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001694void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001695 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1696 // If any of the external buttons are already pressed by the touch device, ignore them.
1697 const int32_t pressedButtons = ~mCurrentRawState.buttonState & mExternalStylusState.buttons;
1698 const int32_t releasedButtons =
1699 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1700
1701 mCurrentRawState.buttonState |= pressedButtons;
1702 mCurrentRawState.buttonState &= ~releasedButtons;
1703
1704 mExternalStylusButtonsApplied |= pressedButtons;
1705 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001706 }
1707}
1708
1709void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1710 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1711 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001712 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1713 return;
1714 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001715
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001716 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1717 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1718 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1719 : 0.f;
1720 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1721 pressure = *mExternalStylusState.pressure;
1722 }
1723 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1724 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001725
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001726 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001727 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001728 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001729 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001730 }
1731}
1732
1733bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001734 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001735 return false;
1736 }
1737
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001738 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001739 if (mFusedStylusPointerId &&
1740 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001741 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001742 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001743 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001744 }
1745
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001746 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1747 state.rawPointerData.pointerCount != 0;
1748 if (!initialDown) {
1749 return false;
1750 }
1751
1752 if (!mExternalStylusState.pressure) {
1753 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1754 return false;
1755 }
1756
1757 if (*mExternalStylusState.pressure != 0.0f) {
1758 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1759 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1760 return false;
1761 }
1762
1763 if (timeout) {
1764 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1765 mFusedStylusPointerId.reset();
1766 mExternalStylusFusionTimeout = LLONG_MAX;
1767 return false;
1768 }
1769
1770 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1771 // being processed until we either get pressure data or timeout.
1772 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1773 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1774 }
1775 ALOGD_IF(DEBUG_STYLUS_FUSION,
1776 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1777 mExternalStylusFusionTimeout);
1778 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1779 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001780}
1781
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001782std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1783 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001784 if (mDeviceMode == DeviceMode::POINTER) {
1785 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001786 // Since this is a synthetic event, we can consider its latency to be zero
1787 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001788 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001789 }
Michael Wright227c5542020-07-02 18:30:52 +01001790 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001791 if (mExternalStylusFusionTimeout <= when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001792 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001793 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1794 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1795 }
1796 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001797 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001798}
1799
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001800std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1801 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001802 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001803 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001804 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001805 // The following three cases are handled here:
1806 // - We're in the middle of a fused stream of data;
1807 // - We're waiting on external stylus data before dispatching the initial down; or
1808 // - Only the button state, which is not reported through a specific pointer, has changed.
1809 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001810 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001811 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001812 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001813 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001814}
1815
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001816std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1817 uint32_t policyFlags, bool& outConsumed) {
1818 outConsumed = false;
1819 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001820 // Check for release of a virtual key.
1821 if (mCurrentVirtualKey.down) {
1822 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1823 // Pointer went up while virtual key was down.
1824 mCurrentVirtualKey.down = false;
1825 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001826 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1827 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1828 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001829 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1830 AKEY_EVENT_FLAG_FROM_SYSTEM |
1831 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001832 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001833 outConsumed = true;
1834 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001835 }
1836
1837 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1838 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1839 const RawPointerData::Pointer& pointer =
1840 mCurrentRawState.rawPointerData.pointerForId(id);
1841 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1842 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1843 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001844 outConsumed = true;
1845 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001846 }
1847 }
1848
1849 // Pointer left virtual key area or another pointer also went down.
1850 // Send key cancellation but do not consume the touch yet.
1851 // This is useful when the user swipes through from the virtual key area
1852 // into the main display surface.
1853 mCurrentVirtualKey.down = false;
1854 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001855 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1856 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001857 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1858 AKEY_EVENT_FLAG_FROM_SYSTEM |
1859 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1860 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001861 }
1862 }
1863
1864 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1865 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1866 // Pointer just went down. Check for virtual key press or off-screen touches.
1867 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1868 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001869 // Skip checking whether the pointer is inside the physical frame if the device is in
1870 // unscaled mode.
1871 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1872 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001873 // If exactly one pointer went down, check for virtual key hit.
1874 // Otherwise we will drop the entire stroke.
1875 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1876 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1877 if (virtualKey) {
1878 mCurrentVirtualKey.down = true;
1879 mCurrentVirtualKey.downTime = when;
1880 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1881 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1882 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001883 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1884 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001885
1886 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001887 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1888 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1889 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001890 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1891 AKEY_EVENT_ACTION_DOWN,
1892 AKEY_EVENT_FLAG_FROM_SYSTEM |
1893 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001894 }
1895 }
1896 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001897 outConsumed = true;
1898 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001899 }
1900 }
1901
1902 // Disable all virtual key touches that happen within a short time interval of the
1903 // most recent touch within the screen area. The idea is to filter out stray
1904 // virtual key presses when interacting with the touch screen.
1905 //
1906 // Problems we're trying to solve:
1907 //
1908 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1909 // virtual key area that is implemented by a separate touch panel and accidentally
1910 // triggers a virtual key.
1911 //
1912 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1913 // area and accidentally triggers a virtual key. This often happens when virtual keys
1914 // are layed out below the screen near to where the on screen keyboard's space bar
1915 // is displayed.
1916 if (mConfig.virtualKeyQuietTime > 0 &&
1917 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001918 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001919 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001920 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001921}
1922
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001923NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1924 uint32_t policyFlags, int32_t keyEventAction,
1925 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001926 int32_t keyCode = mCurrentVirtualKey.keyCode;
1927 int32_t scanCode = mCurrentVirtualKey.scanCode;
1928 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001929 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001930 policyFlags |= POLICY_FLAG_VIRTUAL;
1931
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001932 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1933 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1934 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001935}
1936
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001937std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1938 uint32_t policyFlags) {
1939 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001940 if (mCurrentMotionAborted) {
1941 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001942 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001943 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001944 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1945 if (!currentIdBits.isEmpty()) {
1946 int32_t metaState = getContext()->getGlobalMetaState();
1947 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001948 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001949 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1950 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001951 mCurrentCookedState.cookedPointerData.pointerProperties,
1952 mCurrentCookedState.cookedPointerData.pointerCoords,
1953 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1954 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1955 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001956 mCurrentMotionAborted = true;
1957 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001958 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001959}
1960
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001961// Updates pointer coords and properties for pointers with specified ids that have moved.
1962// Returns true if any of them changed.
1963static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1964 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1965 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1966 BitSet32 idBits) {
1967 bool changed = false;
1968 while (!idBits.isEmpty()) {
1969 uint32_t id = idBits.clearFirstMarkedBit();
1970 uint32_t inIndex = inIdToIndex[id];
1971 uint32_t outIndex = outIdToIndex[id];
1972
1973 const PointerProperties& curInProperties = inProperties[inIndex];
1974 const PointerCoords& curInCoords = inCoords[inIndex];
1975 PointerProperties& curOutProperties = outProperties[outIndex];
1976 PointerCoords& curOutCoords = outCoords[outIndex];
1977
1978 if (curInProperties != curOutProperties) {
1979 curOutProperties.copyFrom(curInProperties);
1980 changed = true;
1981 }
1982
1983 if (curInCoords != curOutCoords) {
1984 curOutCoords.copyFrom(curInCoords);
1985 changed = true;
1986 }
1987 }
1988 return changed;
1989}
1990
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001991std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1992 uint32_t policyFlags) {
1993 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001994 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1995 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1996 int32_t metaState = getContext()->getGlobalMetaState();
1997 int32_t buttonState = mCurrentCookedState.buttonState;
1998
1999 if (currentIdBits == lastIdBits) {
2000 if (!currentIdBits.isEmpty()) {
2001 // No pointer id changes so this is a move event.
2002 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002003 out.push_back(
2004 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2005 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2006 mCurrentCookedState.cookedPointerData.pointerProperties,
2007 mCurrentCookedState.cookedPointerData.pointerCoords,
2008 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2009 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2010 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002011 }
2012 } else {
2013 // There may be pointers going up and pointers going down and pointers moving
2014 // all at the same time.
2015 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2016 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2017 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2018 BitSet32 dispatchedIdBits(lastIdBits.value);
2019
2020 // Update last coordinates of pointers that have moved so that we observe the new
2021 // pointer positions at the same time as other pointers that have just gone up.
2022 bool moveNeeded =
2023 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2024 mCurrentCookedState.cookedPointerData.pointerCoords,
2025 mCurrentCookedState.cookedPointerData.idToIndex,
2026 mLastCookedState.cookedPointerData.pointerProperties,
2027 mLastCookedState.cookedPointerData.pointerCoords,
2028 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2029 if (buttonState != mLastCookedState.buttonState) {
2030 moveNeeded = true;
2031 }
2032
2033 // Dispatch pointer up events.
2034 while (!upIdBits.isEmpty()) {
2035 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002036 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002037 if (isCanceled) {
2038 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2039 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002040 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2041 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2042 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2043 buttonState, 0,
2044 mLastCookedState.cookedPointerData.pointerProperties,
2045 mLastCookedState.cookedPointerData.pointerCoords,
2046 mLastCookedState.cookedPointerData.idToIndex,
2047 dispatchedIdBits, upId, mOrientedXPrecision,
2048 mOrientedYPrecision, mDownTime,
2049 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002050 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002051 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002052 }
2053
2054 // Dispatch move events if any of the remaining pointers moved from their old locations.
2055 // Although applications receive new locations as part of individual pointer up
2056 // events, they do not generally handle them except when presented in a move event.
2057 if (moveNeeded && !moveIdBits.isEmpty()) {
2058 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002059 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2060 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2061 mCurrentCookedState.cookedPointerData.pointerProperties,
2062 mCurrentCookedState.cookedPointerData.pointerCoords,
2063 mCurrentCookedState.cookedPointerData.idToIndex,
2064 dispatchedIdBits, -1, mOrientedXPrecision,
2065 mOrientedYPrecision, mDownTime,
2066 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002067 }
2068
2069 // Dispatch pointer down events using the new pointer locations.
2070 while (!downIdBits.isEmpty()) {
2071 uint32_t downId = downIdBits.clearFirstMarkedBit();
2072 dispatchedIdBits.markBit(downId);
2073
2074 if (dispatchedIdBits.count() == 1) {
2075 // First pointer is going down. Set down time.
2076 mDownTime = when;
2077 }
2078
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002079 out.push_back(
2080 dispatchMotion(when, readTime, policyFlags, mSource,
2081 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2082 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2083 mCurrentCookedState.cookedPointerData.pointerCoords,
2084 mCurrentCookedState.cookedPointerData.idToIndex,
2085 dispatchedIdBits, downId, mOrientedXPrecision,
2086 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002087 }
2088 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002089 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002090}
2091
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002092std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2093 uint32_t policyFlags) {
2094 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002095 if (mSentHoverEnter &&
2096 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2097 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2098 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002099 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2100 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2101 mLastCookedState.buttonState, 0,
2102 mLastCookedState.cookedPointerData.pointerProperties,
2103 mLastCookedState.cookedPointerData.pointerCoords,
2104 mLastCookedState.cookedPointerData.idToIndex,
2105 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2106 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2107 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002108 mSentHoverEnter = false;
2109 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002110 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002111}
2112
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002113std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2114 uint32_t policyFlags) {
2115 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002116 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2117 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2118 int32_t metaState = getContext()->getGlobalMetaState();
2119 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002120 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2121 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2122 mCurrentRawState.buttonState, 0,
2123 mCurrentCookedState.cookedPointerData.pointerProperties,
2124 mCurrentCookedState.cookedPointerData.pointerCoords,
2125 mCurrentCookedState.cookedPointerData.idToIndex,
2126 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2127 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2128 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002129 mSentHoverEnter = true;
2130 }
2131
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002132 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2133 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2134 mCurrentRawState.buttonState, 0,
2135 mCurrentCookedState.cookedPointerData.pointerProperties,
2136 mCurrentCookedState.cookedPointerData.pointerCoords,
2137 mCurrentCookedState.cookedPointerData.idToIndex,
2138 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2139 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2140 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002141 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002142 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002143}
2144
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002145std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2146 uint32_t policyFlags) {
2147 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002148 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2149 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2150 const int32_t metaState = getContext()->getGlobalMetaState();
2151 int32_t buttonState = mLastCookedState.buttonState;
2152 while (!releasedButtons.isEmpty()) {
2153 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2154 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002155 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2156 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2157 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002158 mLastCookedState.cookedPointerData.pointerProperties,
2159 mLastCookedState.cookedPointerData.pointerCoords,
2160 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002161 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2162 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002163 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002164 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002165}
2166
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002167std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2168 uint32_t policyFlags) {
2169 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002170 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2171 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2172 const int32_t metaState = getContext()->getGlobalMetaState();
2173 int32_t buttonState = mLastCookedState.buttonState;
2174 while (!pressedButtons.isEmpty()) {
2175 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2176 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002177 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2178 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2179 buttonState, 0,
2180 mCurrentCookedState.cookedPointerData.pointerProperties,
2181 mCurrentCookedState.cookedPointerData.pointerCoords,
2182 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2183 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2184 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002185 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002186 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002187}
2188
2189const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2190 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2191 return cookedPointerData.touchingIdBits;
2192 }
2193 return cookedPointerData.hoveringIdBits;
2194}
2195
2196void TouchInputMapper::cookPointerData() {
2197 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2198
2199 mCurrentCookedState.cookedPointerData.clear();
2200 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2201 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2202 mCurrentRawState.rawPointerData.hoveringIdBits;
2203 mCurrentCookedState.cookedPointerData.touchingIdBits =
2204 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002205 mCurrentCookedState.cookedPointerData.canceledIdBits =
2206 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002207
2208 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2209 mCurrentCookedState.buttonState = 0;
2210 } else {
2211 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2212 }
2213
2214 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002215 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002216 for (uint32_t i = 0; i < currentPointerCount; i++) {
2217 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2218
2219 // Size
2220 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2221 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002222 case Calibration::SizeCalibration::GEOMETRIC:
2223 case Calibration::SizeCalibration::DIAMETER:
2224 case Calibration::SizeCalibration::BOX:
2225 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002226 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2227 touchMajor = in.touchMajor;
2228 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2229 toolMajor = in.toolMajor;
2230 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2231 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2232 : in.touchMajor;
2233 } else if (mRawPointerAxes.touchMajor.valid) {
2234 toolMajor = touchMajor = in.touchMajor;
2235 toolMinor = touchMinor =
2236 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2237 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2238 : in.touchMajor;
2239 } else if (mRawPointerAxes.toolMajor.valid) {
2240 touchMajor = toolMajor = in.toolMajor;
2241 touchMinor = toolMinor =
2242 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2243 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2244 : in.toolMajor;
2245 } else {
2246 ALOG_ASSERT(false,
2247 "No touch or tool axes. "
2248 "Size calibration should have been resolved to NONE.");
2249 touchMajor = 0;
2250 touchMinor = 0;
2251 toolMajor = 0;
2252 toolMinor = 0;
2253 size = 0;
2254 }
2255
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002256 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002257 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2258 if (touchingCount > 1) {
2259 touchMajor /= touchingCount;
2260 touchMinor /= touchingCount;
2261 toolMajor /= touchingCount;
2262 toolMinor /= touchingCount;
2263 size /= touchingCount;
2264 }
2265 }
2266
Michael Wright227c5542020-07-02 18:30:52 +01002267 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002268 touchMajor *= mGeometricScale;
2269 touchMinor *= mGeometricScale;
2270 toolMajor *= mGeometricScale;
2271 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002272 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002273 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2274 touchMinor = touchMajor;
2275 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2276 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002277 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002278 touchMinor = touchMajor;
2279 toolMinor = toolMajor;
2280 }
2281
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002282 mCalibration.applySizeScaleAndBias(touchMajor);
2283 mCalibration.applySizeScaleAndBias(touchMinor);
2284 mCalibration.applySizeScaleAndBias(toolMajor);
2285 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002286 size *= mSizeScale;
2287 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002288 case Calibration::SizeCalibration::DEFAULT:
2289 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2290 break;
2291 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002292 touchMajor = 0;
2293 touchMinor = 0;
2294 toolMajor = 0;
2295 toolMinor = 0;
2296 size = 0;
2297 break;
2298 }
2299
2300 // Pressure
2301 float pressure;
2302 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002303 case Calibration::PressureCalibration::PHYSICAL:
2304 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002305 pressure = in.pressure * mPressureScale;
2306 break;
2307 default:
2308 pressure = in.isHovering ? 0 : 1;
2309 break;
2310 }
2311
2312 // Tilt and Orientation
2313 float tilt;
2314 float orientation;
2315 if (mHaveTilt) {
2316 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2317 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2318 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2319 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2320 } else {
2321 tilt = 0;
2322
2323 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002324 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002325 orientation = in.orientation * mOrientationScale;
2326 break;
Michael Wright227c5542020-07-02 18:30:52 +01002327 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002328 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2329 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2330 if (c1 != 0 || c2 != 0) {
2331 orientation = atan2f(c1, c2) * 0.5f;
2332 float confidence = hypotf(c1, c2);
2333 float scale = 1.0f + confidence / 16.0f;
2334 touchMajor *= scale;
2335 touchMinor /= scale;
2336 toolMajor *= scale;
2337 toolMinor /= scale;
2338 } else {
2339 orientation = 0;
2340 }
2341 break;
2342 }
2343 default:
2344 orientation = 0;
2345 }
2346 }
2347
2348 // Distance
2349 float distance;
2350 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002351 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002352 distance = in.distance * mDistanceScale;
2353 break;
2354 default:
2355 distance = 0;
2356 }
2357
2358 // Coverage
2359 int32_t rawLeft, rawTop, rawRight, rawBottom;
2360 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002361 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002362 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2363 rawRight = in.toolMinor & 0x0000ffff;
2364 rawBottom = in.toolMajor & 0x0000ffff;
2365 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2366 break;
2367 default:
2368 rawLeft = rawTop = rawRight = rawBottom = 0;
2369 break;
2370 }
2371
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002372 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2373 vec2 transformed = {in.x, in.y};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002374 // TODO: Adjust coverage coords?
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002375 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2376 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002377
Prabir Pradhan1728b212021-10-19 16:00:03 -07002378 // Adjust X, Y, and coverage coords for input device orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002379 float left, top, right, bottom;
2380
Prabir Pradhan1728b212021-10-19 16:00:03 -07002381 switch (mInputDeviceOrientation) {
Michael Wrighta9cf4192022-12-01 23:46:39 +00002382 case ui::ROTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002383 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
2384 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2385 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2386 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002387 orientation -= M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002388 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002389 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002390 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391 }
2392 break;
Michael Wrighta9cf4192022-12-01 23:46:39 +00002393 case ui::ROTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002394 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2395 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002396 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2397 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002398 orientation -= M_PI;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002399 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002400 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002401 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002402 }
2403 break;
Michael Wrighta9cf4192022-12-01 23:46:39 +00002404 case ui::ROTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002405 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2406 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002407 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2408 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002409 orientation += M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002410 if (mOrientedRanges.orientation && orientation > mOrientedRanges.orientation->max) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002411 orientation -=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002412 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002413 }
2414 break;
2415 default:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002416 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
2417 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2418 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2419 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002420 break;
2421 }
2422
2423 // Write output coords.
2424 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2425 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002426 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2427 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002428 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2429 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2430 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2431 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2432 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2433 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2434 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002435 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002436 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2437 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2438 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2439 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2440 } else {
2441 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2442 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2443 }
2444
Chris Ye364fdb52020-08-05 15:07:56 -07002445 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002446 uint32_t id = in.id;
2447 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2448 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2449 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002450 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2451 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002452 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2453 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2454 }
2455
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002456 // Write output properties.
2457 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002458 properties.clear();
2459 properties.id = id;
2460 properties.toolType = in.toolType;
2461
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002462 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002463 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002464 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002465 }
2466}
2467
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002468std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2469 uint32_t policyFlags,
2470 PointerUsage pointerUsage) {
2471 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002472 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002473 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002474 mPointerUsage = pointerUsage;
2475 }
2476
2477 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002478 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002479 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002480 break;
Michael Wright227c5542020-07-02 18:30:52 +01002481 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002482 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002483 break;
Michael Wright227c5542020-07-02 18:30:52 +01002484 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002485 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002486 break;
Michael Wright227c5542020-07-02 18:30:52 +01002487 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002488 break;
2489 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002490 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002491}
2492
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002493std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2494 uint32_t policyFlags) {
2495 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002496 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002497 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002498 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002499 break;
Michael Wright227c5542020-07-02 18:30:52 +01002500 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002501 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002502 break;
Michael Wright227c5542020-07-02 18:30:52 +01002503 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002504 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002505 break;
Michael Wright227c5542020-07-02 18:30:52 +01002506 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002507 break;
2508 }
2509
Michael Wright227c5542020-07-02 18:30:52 +01002510 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002511 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002512}
2513
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002514std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2515 uint32_t policyFlags,
2516 bool isTimeout) {
2517 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002518 // Update current gesture coordinates.
2519 bool cancelPreviousGesture, finishPreviousGesture;
2520 bool sendEvents =
2521 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2522 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002523 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002524 }
2525 if (finishPreviousGesture) {
2526 cancelPreviousGesture = false;
2527 }
2528
2529 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002530 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002531 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002532 if (finishPreviousGesture || cancelPreviousGesture) {
2533 mPointerController->clearSpots();
2534 }
2535
Michael Wright227c5542020-07-02 18:30:52 +01002536 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002537 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2538 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002539 mPointerGesture.currentGestureIdBits,
2540 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002541 }
2542 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002543 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002544 }
2545
2546 // Show or hide the pointer if needed.
2547 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002548 case PointerGesture::Mode::NEUTRAL:
2549 case PointerGesture::Mode::QUIET:
2550 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2551 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002552 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002553 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002554 }
2555 break;
Michael Wright227c5542020-07-02 18:30:52 +01002556 case PointerGesture::Mode::TAP:
2557 case PointerGesture::Mode::TAP_DRAG:
2558 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2559 case PointerGesture::Mode::HOVER:
2560 case PointerGesture::Mode::PRESS:
2561 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002562 // Unfade the pointer when the current gesture manipulates the
2563 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002564 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002565 break;
Michael Wright227c5542020-07-02 18:30:52 +01002566 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002567 // Fade the pointer when the current gesture manipulates a different
2568 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002569 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002570 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002571 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002572 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002573 }
2574 break;
2575 }
2576
2577 // Send events!
2578 int32_t metaState = getContext()->getGlobalMetaState();
2579 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002580 const MotionClassification classification =
2581 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2582 ? MotionClassification::TWO_FINGER_SWIPE
2583 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002584
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002585 uint32_t flags = 0;
2586
2587 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2588 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2589 }
2590
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002591 // Update last coordinates of pointers that have moved so that we observe the new
2592 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002593 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2594 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2595 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2596 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2597 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2598 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002599 bool moveNeeded = false;
2600 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2601 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2602 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2603 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2604 mPointerGesture.lastGestureIdBits.value);
2605 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2606 mPointerGesture.currentGestureCoords,
2607 mPointerGesture.currentGestureIdToIndex,
2608 mPointerGesture.lastGestureProperties,
2609 mPointerGesture.lastGestureCoords,
2610 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2611 if (buttonState != mLastCookedState.buttonState) {
2612 moveNeeded = true;
2613 }
2614 }
2615
2616 // Send motion events for all pointers that went up or were canceled.
2617 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2618 if (!dispatchedGestureIdBits.isEmpty()) {
2619 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002620 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002621 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002622 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002623 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2624 mPointerGesture.lastGestureProperties,
2625 mPointerGesture.lastGestureCoords,
2626 mPointerGesture.lastGestureIdToIndex,
2627 dispatchedGestureIdBits, -1, 0, 0,
2628 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002629
2630 dispatchedGestureIdBits.clear();
2631 } else {
2632 BitSet32 upGestureIdBits;
2633 if (finishPreviousGesture) {
2634 upGestureIdBits = dispatchedGestureIdBits;
2635 } else {
2636 upGestureIdBits.value =
2637 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2638 }
2639 while (!upGestureIdBits.isEmpty()) {
2640 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2641
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002642 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2643 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2644 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2645 mPointerGesture.lastGestureProperties,
2646 mPointerGesture.lastGestureCoords,
2647 mPointerGesture.lastGestureIdToIndex,
2648 dispatchedGestureIdBits, id, 0, 0,
2649 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002650
2651 dispatchedGestureIdBits.clearBit(id);
2652 }
2653 }
2654 }
2655
2656 // Send motion events for all pointers that moved.
2657 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002658 out.push_back(
2659 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2660 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2661 mPointerGesture.currentGestureProperties,
2662 mPointerGesture.currentGestureCoords,
2663 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2664 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002665 }
2666
2667 // Send motion events for all pointers that went down.
2668 if (down) {
2669 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2670 ~dispatchedGestureIdBits.value);
2671 while (!downGestureIdBits.isEmpty()) {
2672 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2673 dispatchedGestureIdBits.markBit(id);
2674
2675 if (dispatchedGestureIdBits.count() == 1) {
2676 mPointerGesture.downTime = when;
2677 }
2678
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002679 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2680 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2681 buttonState, 0, mPointerGesture.currentGestureProperties,
2682 mPointerGesture.currentGestureCoords,
2683 mPointerGesture.currentGestureIdToIndex,
2684 dispatchedGestureIdBits, id, 0, 0,
2685 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002686 }
2687 }
2688
2689 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002690 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002691 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2692 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2693 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2694 mPointerGesture.currentGestureProperties,
2695 mPointerGesture.currentGestureCoords,
2696 mPointerGesture.currentGestureIdToIndex,
2697 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2698 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002699 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2700 // Synthesize a hover move event after all pointers go up to indicate that
2701 // the pointer is hovering again even if the user is not currently touching
2702 // the touch pad. This ensures that a view will receive a fresh hover enter
2703 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002704 float x, y;
2705 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002706
2707 PointerProperties pointerProperties;
2708 pointerProperties.clear();
2709 pointerProperties.id = 0;
2710 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2711
2712 PointerCoords pointerCoords;
2713 pointerCoords.clear();
2714 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2715 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2716
2717 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002718 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2719 mSource, displayId, policyFlags,
2720 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2721 buttonState, MotionClassification::NONE,
2722 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2723 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2724 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002725 }
2726
2727 // Update state.
2728 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2729 if (!down) {
2730 mPointerGesture.lastGestureIdBits.clear();
2731 } else {
2732 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2733 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2734 uint32_t id = idBits.clearFirstMarkedBit();
2735 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2736 mPointerGesture.lastGestureProperties[index].copyFrom(
2737 mPointerGesture.currentGestureProperties[index]);
2738 mPointerGesture.lastGestureCoords[index].copyFrom(
2739 mPointerGesture.currentGestureCoords[index]);
2740 mPointerGesture.lastGestureIdToIndex[id] = index;
2741 }
2742 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002743 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002744}
2745
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002746std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2747 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002748 const MotionClassification classification =
2749 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2750 ? MotionClassification::TWO_FINGER_SWIPE
2751 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002752 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002753 // Cancel previously dispatches pointers.
2754 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2755 int32_t metaState = getContext()->getGlobalMetaState();
2756 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002757 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002758 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2759 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002760 mPointerGesture.lastGestureProperties,
2761 mPointerGesture.lastGestureCoords,
2762 mPointerGesture.lastGestureIdToIndex,
2763 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2764 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002765 }
2766
2767 // Reset the current pointer gesture.
2768 mPointerGesture.reset();
2769 mPointerVelocityControl.reset();
2770
2771 // Remove any current spots.
2772 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002773 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002774 mPointerController->clearSpots();
2775 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002776 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002777}
2778
2779bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2780 bool* outFinishPreviousGesture, bool isTimeout) {
2781 *outCancelPreviousGesture = false;
2782 *outFinishPreviousGesture = false;
2783
2784 // Handle TAP timeout.
2785 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002786 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002787
Michael Wright227c5542020-07-02 18:30:52 +01002788 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002789 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2790 // The tap/drag timeout has not yet expired.
2791 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2792 mConfig.pointerGestureTapDragInterval);
2793 } else {
2794 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002795 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002796 *outFinishPreviousGesture = true;
2797
2798 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002799 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002800 mPointerGesture.currentGestureIdBits.clear();
2801
2802 mPointerVelocityControl.reset();
2803 return true;
2804 }
2805 }
2806
2807 // We did not handle this timeout.
2808 return false;
2809 }
2810
2811 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2812 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2813
2814 // Update the velocity tracker.
2815 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002816 std::vector<float> positionsX;
2817 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002818 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002819 uint32_t id = idBits.clearFirstMarkedBit();
2820 const RawPointerData::Pointer& pointer =
2821 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002822 positionsX.push_back(pointer.x * mPointerXMovementScale);
2823 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002824 }
2825 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002826 {{AMOTION_EVENT_AXIS_X, positionsX},
2827 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002828 }
2829
2830 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2831 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002832 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2833 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2834 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002835 mPointerGesture.resetTap();
2836 }
2837
2838 // Pick a new active touch id if needed.
2839 // Choose an arbitrary pointer that just went down, if there is one.
2840 // Otherwise choose an arbitrary remaining pointer.
2841 // This guarantees we always have an active touch id when there is at least one pointer.
2842 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002843 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002844 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002845 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002846 mPointerGesture.firstTouchTime = when;
2847 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002848 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2849 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2850 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2851 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002852 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002853 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002854
2855 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002856 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002857 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002858 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2859 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2860 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002861 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002862 *outFinishPreviousGesture = true;
2863 }
2864
2865 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002866 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002867 mPointerGesture.currentGestureIdBits.clear();
2868
2869 mPointerVelocityControl.reset();
2870 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2871 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2872 // The pointer follows the active touch point.
2873 // Emit DOWN, MOVE, UP events at the pointer location.
2874 //
2875 // Only the active touch matters; other fingers are ignored. This policy helps
2876 // to handle the case where the user places a second finger on the touch pad
2877 // to apply the necessary force to depress an integrated button below the surface.
2878 // We don't want the second finger to be delivered to applications.
2879 //
2880 // For this to work well, we need to make sure to track the pointer that is really
2881 // active. If the user first puts one finger down to click then adds another
2882 // finger to drag then the active pointer should switch to the finger that is
2883 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002884 ALOGD_IF(DEBUG_GESTURES,
2885 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2886 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002887 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002888 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002889 *outFinishPreviousGesture = true;
2890 mPointerGesture.activeGestureId = 0;
2891 }
2892
2893 // Switch pointers if needed.
2894 // Find the fastest pointer and follow it.
2895 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002896 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002897 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002898 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002899 ALOGD_IF(DEBUG_GESTURES,
2900 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2901 "bestSpeed=%0.3f",
2902 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002903 }
2904 }
2905
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002906 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002907 // When using spots, the click will occur at the position of the anchor
2908 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002909 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002910 } else {
2911 mPointerVelocityControl.reset();
2912 }
2913
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002914 float x, y;
2915 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002916
Michael Wright227c5542020-07-02 18:30:52 +01002917 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002918 mPointerGesture.currentGestureIdBits.clear();
2919 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2920 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2921 mPointerGesture.currentGestureProperties[0].clear();
2922 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2923 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2924 mPointerGesture.currentGestureCoords[0].clear();
2925 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2926 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2927 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2928 } else if (currentFingerCount == 0) {
2929 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002930 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002931 *outFinishPreviousGesture = true;
2932 }
2933
2934 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2935 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2936 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002937 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2938 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002939 lastFingerCount == 1) {
2940 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002941 float x, y;
2942 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002943 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2944 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002945 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002946
2947 mPointerGesture.tapUpTime = when;
2948 getContext()->requestTimeoutAtTime(when +
2949 mConfig.pointerGestureTapDragInterval);
2950
2951 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002952 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002953 mPointerGesture.currentGestureIdBits.clear();
2954 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2955 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2956 mPointerGesture.currentGestureProperties[0].clear();
2957 mPointerGesture.currentGestureProperties[0].id =
2958 mPointerGesture.activeGestureId;
2959 mPointerGesture.currentGestureProperties[0].toolType =
2960 AMOTION_EVENT_TOOL_TYPE_FINGER;
2961 mPointerGesture.currentGestureCoords[0].clear();
2962 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2963 mPointerGesture.tapX);
2964 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2965 mPointerGesture.tapY);
2966 mPointerGesture.currentGestureCoords[0]
2967 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2968
2969 tapped = true;
2970 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002971 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2972 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002973 }
2974 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002975 if (DEBUG_GESTURES) {
2976 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2977 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2978 (when - mPointerGesture.tapDownTime) * 0.000001f);
2979 } else {
2980 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2981 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002982 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002983 }
2984 }
2985
2986 mPointerVelocityControl.reset();
2987
2988 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002989 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002990 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002991 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002992 mPointerGesture.currentGestureIdBits.clear();
2993 }
2994 } else if (currentFingerCount == 1) {
2995 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2996 // The pointer follows the active touch point.
2997 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2998 // When in TAP_DRAG, emit MOVE events at the pointer location.
2999 ALOG_ASSERT(activeTouchId >= 0);
3000
Michael Wright227c5542020-07-02 18:30:52 +01003001 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
3002 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003003 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003004 float x, y;
3005 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003006 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
3007 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01003008 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003009 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003010 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3011 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003012 }
3013 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003014 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3015 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003016 }
Michael Wright227c5542020-07-02 18:30:52 +01003017 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3018 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003019 }
3020
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003021 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003022 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003023 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003024 } else {
3025 mPointerVelocityControl.reset();
3026 }
3027
3028 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003029 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003030 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003031 down = true;
3032 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003033 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003034 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003035 *outFinishPreviousGesture = true;
3036 }
3037 mPointerGesture.activeGestureId = 0;
3038 down = false;
3039 }
3040
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003041 float x, y;
3042 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003043
3044 mPointerGesture.currentGestureIdBits.clear();
3045 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3046 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3047 mPointerGesture.currentGestureProperties[0].clear();
3048 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3049 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3050 mPointerGesture.currentGestureCoords[0].clear();
3051 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3052 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3053 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3054 down ? 1.0f : 0.0f);
3055
3056 if (lastFingerCount == 0 && currentFingerCount != 0) {
3057 mPointerGesture.resetTap();
3058 mPointerGesture.tapDownTime = when;
3059 mPointerGesture.tapX = x;
3060 mPointerGesture.tapY = y;
3061 }
3062 } else {
3063 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003064 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003065 }
3066
3067 mPointerController->setButtonState(mCurrentRawState.buttonState);
3068
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003069 if (DEBUG_GESTURES) {
3070 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3071 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3072 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3073 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3074 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3075 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3076 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3077 uint32_t id = idBits.clearFirstMarkedBit();
3078 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3079 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3080 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3081 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3082 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3083 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3084 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3085 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3086 }
3087 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3088 uint32_t id = idBits.clearFirstMarkedBit();
3089 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3090 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3091 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3092 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3093 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3094 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3095 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3096 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3097 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003098 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003099 return true;
3100}
3101
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003102bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3103 if (mPointerGesture.activeTouchId < 0) {
3104 mPointerGesture.resetQuietTime();
3105 return false;
3106 }
3107
3108 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3109 return true;
3110 }
3111
3112 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3113 bool isQuietTime = false;
3114 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3115 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3116 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3117 currentFingerCount < 2) {
3118 // Enter quiet time when exiting swipe or freeform state.
3119 // This is to prevent accidentally entering the hover state and flinging the
3120 // pointer when finishing a swipe and there is still one pointer left onscreen.
3121 isQuietTime = true;
3122 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3123 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3124 // Enter quiet time when releasing the button and there are still two or more
3125 // fingers down. This may indicate that one finger was used to press the button
3126 // but it has not gone up yet.
3127 isQuietTime = true;
3128 }
3129 if (isQuietTime) {
3130 mPointerGesture.quietTime = when;
3131 }
3132 return isQuietTime;
3133}
3134
3135std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3136 int32_t bestId = -1;
3137 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3138 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3139 uint32_t id = idBits.clearFirstMarkedBit();
3140 std::optional<float> vx =
3141 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3142 std::optional<float> vy =
3143 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3144 if (vx && vy) {
3145 float speed = hypotf(*vx, *vy);
3146 if (speed > bestSpeed) {
3147 bestId = id;
3148 bestSpeed = speed;
3149 }
3150 }
3151 }
3152 return std::make_pair(bestId, bestSpeed);
3153}
3154
3155void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3156 bool* finishPreviousGesture) {
3157 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3158 // to move before deciding what to do.
3159 //
3160 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3161 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3162 // just a press or long-press at the pointer location.
3163 //
3164 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3165 // pointer location.
3166 //
3167 // When the two fingers move enough or when additional fingers are added, we make a decision to
3168 // transition into SWIPE or FREEFORM mode accordingly.
3169 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3170 ALOG_ASSERT(activeTouchId >= 0);
3171
3172 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3173 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3174 bool settled =
3175 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3176 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3177 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3178 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3179 *finishPreviousGesture = true;
3180 } else if (!settled && currentFingerCount > lastFingerCount) {
3181 // Additional pointers have gone down but not yet settled.
3182 // Reset the gesture.
3183 ALOGD_IF(DEBUG_GESTURES,
3184 "Gestures: Resetting gesture since additional pointers went down for "
3185 "MULTITOUCH, settle time remaining %0.3fms",
3186 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3187 when) * 0.000001f);
3188 *cancelPreviousGesture = true;
3189 } else {
3190 // Continue previous gesture.
3191 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3192 }
3193
3194 if (*finishPreviousGesture || *cancelPreviousGesture) {
3195 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3196 mPointerGesture.activeGestureId = 0;
3197 mPointerGesture.referenceIdBits.clear();
3198 mPointerVelocityControl.reset();
3199
3200 // Use the centroid and pointer location as the reference points for the gesture.
3201 ALOGD_IF(DEBUG_GESTURES,
3202 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3203 "%0.3fms",
3204 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3205 when) * 0.000001f);
3206 mCurrentRawState.rawPointerData
3207 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3208 &mPointerGesture.referenceTouchY);
3209 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3210 &mPointerGesture.referenceGestureY);
3211 }
3212
3213 // Clear the reference deltas for fingers not yet included in the reference calculation.
3214 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3215 ~mPointerGesture.referenceIdBits.value);
3216 !idBits.isEmpty();) {
3217 uint32_t id = idBits.clearFirstMarkedBit();
3218 mPointerGesture.referenceDeltas[id].dx = 0;
3219 mPointerGesture.referenceDeltas[id].dy = 0;
3220 }
3221 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3222
3223 // Add delta for all fingers and calculate a common movement delta.
3224 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3225 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3226 mCurrentCookedState.fingerIdBits.value);
3227 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3228 bool first = (idBits == commonIdBits);
3229 uint32_t id = idBits.clearFirstMarkedBit();
3230 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3231 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3232 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3233 delta.dx += cpd.x - lpd.x;
3234 delta.dy += cpd.y - lpd.y;
3235
3236 if (first) {
3237 commonDeltaRawX = delta.dx;
3238 commonDeltaRawY = delta.dy;
3239 } else {
3240 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3241 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3242 }
3243 }
3244
3245 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3246 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3247 float dist[MAX_POINTER_ID + 1];
3248 int32_t distOverThreshold = 0;
3249 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3250 uint32_t id = idBits.clearFirstMarkedBit();
3251 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3252 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3253 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3254 distOverThreshold += 1;
3255 }
3256 }
3257
3258 // Only transition when at least two pointers have moved further than
3259 // the minimum distance threshold.
3260 if (distOverThreshold >= 2) {
3261 if (currentFingerCount > 2) {
3262 // There are more than two pointers, switch to FREEFORM.
3263 ALOGD_IF(DEBUG_GESTURES,
3264 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3265 currentFingerCount);
3266 *cancelPreviousGesture = true;
3267 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3268 } else {
3269 // There are exactly two pointers.
3270 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3271 uint32_t id1 = idBits.clearFirstMarkedBit();
3272 uint32_t id2 = idBits.firstMarkedBit();
3273 const RawPointerData::Pointer& p1 =
3274 mCurrentRawState.rawPointerData.pointerForId(id1);
3275 const RawPointerData::Pointer& p2 =
3276 mCurrentRawState.rawPointerData.pointerForId(id2);
3277 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3278 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3279 // There are two pointers but they are too far apart for a SWIPE,
3280 // switch to FREEFORM.
3281 ALOGD_IF(DEBUG_GESTURES,
3282 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3283 mutualDistance, mPointerGestureMaxSwipeWidth);
3284 *cancelPreviousGesture = true;
3285 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3286 } else {
3287 // There are two pointers. Wait for both pointers to start moving
3288 // before deciding whether this is a SWIPE or FREEFORM gesture.
3289 float dist1 = dist[id1];
3290 float dist2 = dist[id2];
3291 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3292 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3293 // Calculate the dot product of the displacement vectors.
3294 // When the vectors are oriented in approximately the same direction,
3295 // the angle betweeen them is near zero and the cosine of the angle
3296 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3297 // mag(v2).
3298 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3299 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3300 float dx1 = delta1.dx * mPointerXZoomScale;
3301 float dy1 = delta1.dy * mPointerYZoomScale;
3302 float dx2 = delta2.dx * mPointerXZoomScale;
3303 float dy2 = delta2.dy * mPointerYZoomScale;
3304 float dot = dx1 * dx2 + dy1 * dy2;
3305 float cosine = dot / (dist1 * dist2); // denominator always > 0
3306 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3307 // Pointers are moving in the same direction. Switch to SWIPE.
3308 ALOGD_IF(DEBUG_GESTURES,
3309 "Gestures: PRESS transitioned to SWIPE, "
3310 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3311 "cosine %0.3f >= %0.3f",
3312 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3313 mConfig.pointerGestureMultitouchMinDistance, cosine,
3314 mConfig.pointerGestureSwipeTransitionAngleCosine);
3315 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3316 } else {
3317 // Pointers are moving in different directions. Switch to FREEFORM.
3318 ALOGD_IF(DEBUG_GESTURES,
3319 "Gestures: PRESS transitioned to FREEFORM, "
3320 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3321 "cosine %0.3f < %0.3f",
3322 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3323 mConfig.pointerGestureMultitouchMinDistance, cosine,
3324 mConfig.pointerGestureSwipeTransitionAngleCosine);
3325 *cancelPreviousGesture = true;
3326 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3327 }
3328 }
3329 }
3330 }
3331 }
3332 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3333 // Switch from SWIPE to FREEFORM if additional pointers go down.
3334 // Cancel previous gesture.
3335 if (currentFingerCount > 2) {
3336 ALOGD_IF(DEBUG_GESTURES,
3337 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3338 currentFingerCount);
3339 *cancelPreviousGesture = true;
3340 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3341 }
3342 }
3343
3344 // Move the reference points based on the overall group motion of the fingers
3345 // except in PRESS mode while waiting for a transition to occur.
3346 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3347 (commonDeltaRawX || commonDeltaRawY)) {
3348 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3349 uint32_t id = idBits.clearFirstMarkedBit();
3350 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3351 delta.dx = 0;
3352 delta.dy = 0;
3353 }
3354
3355 mPointerGesture.referenceTouchX += commonDeltaRawX;
3356 mPointerGesture.referenceTouchY += commonDeltaRawY;
3357
3358 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3359 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3360
3361 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3362 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3363
3364 mPointerGesture.referenceGestureX += commonDeltaX;
3365 mPointerGesture.referenceGestureY += commonDeltaY;
3366 }
3367
3368 // Report gestures.
3369 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3370 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3371 // PRESS or SWIPE mode.
3372 ALOGD_IF(DEBUG_GESTURES,
3373 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3374 "currentTouchPointerCount=%d",
3375 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3376 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3377
3378 mPointerGesture.currentGestureIdBits.clear();
3379 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3380 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3381 mPointerGesture.currentGestureProperties[0].clear();
3382 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3383 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3384 mPointerGesture.currentGestureCoords[0].clear();
3385 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3386 mPointerGesture.referenceGestureX);
3387 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3388 mPointerGesture.referenceGestureY);
3389 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3390 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3391 float xOffset = static_cast<float>(commonDeltaRawX) /
3392 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3393 float yOffset = static_cast<float>(commonDeltaRawY) /
3394 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3395 mPointerGesture.currentGestureCoords[0]
3396 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3397 mPointerGesture.currentGestureCoords[0]
3398 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3399 }
3400 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3401 // FREEFORM mode.
3402 ALOGD_IF(DEBUG_GESTURES,
3403 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3404 "currentTouchPointerCount=%d",
3405 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3406 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3407
3408 mPointerGesture.currentGestureIdBits.clear();
3409
3410 BitSet32 mappedTouchIdBits;
3411 BitSet32 usedGestureIdBits;
3412 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3413 // Initially, assign the active gesture id to the active touch point
3414 // if there is one. No other touch id bits are mapped yet.
3415 if (!*cancelPreviousGesture) {
3416 mappedTouchIdBits.markBit(activeTouchId);
3417 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3418 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3419 mPointerGesture.activeGestureId;
3420 } else {
3421 mPointerGesture.activeGestureId = -1;
3422 }
3423 } else {
3424 // Otherwise, assume we mapped all touches from the previous frame.
3425 // Reuse all mappings that are still applicable.
3426 mappedTouchIdBits.value =
3427 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3428 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3429
3430 // Check whether we need to choose a new active gesture id because the
3431 // current went went up.
3432 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3433 ~mCurrentCookedState.fingerIdBits.value);
3434 !upTouchIdBits.isEmpty();) {
3435 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3436 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3437 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3438 mPointerGesture.activeGestureId = -1;
3439 break;
3440 }
3441 }
3442 }
3443
3444 ALOGD_IF(DEBUG_GESTURES,
3445 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3446 "activeGestureId=%d",
3447 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3448
3449 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3450 for (uint32_t i = 0; i < currentFingerCount; i++) {
3451 uint32_t touchId = idBits.clearFirstMarkedBit();
3452 uint32_t gestureId;
3453 if (!mappedTouchIdBits.hasBit(touchId)) {
3454 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3455 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3456 ALOGD_IF(DEBUG_GESTURES,
3457 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3458 gestureId);
3459 } else {
3460 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3461 ALOGD_IF(DEBUG_GESTURES,
3462 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3463 touchId, gestureId);
3464 }
3465 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3466 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3467
3468 const RawPointerData::Pointer& pointer =
3469 mCurrentRawState.rawPointerData.pointerForId(touchId);
3470 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3471 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3472 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3473
3474 mPointerGesture.currentGestureProperties[i].clear();
3475 mPointerGesture.currentGestureProperties[i].id = gestureId;
3476 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3477 mPointerGesture.currentGestureCoords[i].clear();
3478 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3479 mPointerGesture.referenceGestureX +
3480 deltaX);
3481 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3482 mPointerGesture.referenceGestureY +
3483 deltaY);
3484 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3485 }
3486
3487 if (mPointerGesture.activeGestureId < 0) {
3488 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3489 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3490 mPointerGesture.activeGestureId);
3491 }
3492 }
3493}
3494
Harry Cutts714d1ad2022-08-24 16:36:43 +00003495void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3496 const RawPointerData::Pointer& currentPointer =
3497 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3498 const RawPointerData::Pointer& lastPointer =
3499 mLastRawState.rawPointerData.pointerForId(pointerId);
3500 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3501 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3502
3503 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3504 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3505
3506 mPointerController->move(deltaX, deltaY);
3507}
3508
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003509std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3510 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003511 mPointerSimple.currentCoords.clear();
3512 mPointerSimple.currentProperties.clear();
3513
3514 bool down, hovering;
3515 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3516 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3517 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003518 mPointerController
3519 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3520 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003521
3522 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3523 down = !hovering;
3524
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003525 float x, y;
3526 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003527 mPointerSimple.currentCoords.copyFrom(
3528 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3529 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3530 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3531 mPointerSimple.currentProperties.id = 0;
3532 mPointerSimple.currentProperties.toolType =
3533 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3534 } else {
3535 down = false;
3536 hovering = false;
3537 }
3538
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003539 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003540}
3541
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003542std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3543 uint32_t policyFlags) {
3544 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003545}
3546
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003547std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3548 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003549 mPointerSimple.currentCoords.clear();
3550 mPointerSimple.currentProperties.clear();
3551
3552 bool down, hovering;
3553 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3554 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003555 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003556 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003557 } else {
3558 mPointerVelocityControl.reset();
3559 }
3560
3561 down = isPointerDown(mCurrentRawState.buttonState);
3562 hovering = !down;
3563
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003564 float x, y;
3565 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003566 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003567 mPointerSimple.currentCoords.copyFrom(
3568 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3569 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3570 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3571 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3572 hovering ? 0.0f : 1.0f);
3573 mPointerSimple.currentProperties.id = 0;
3574 mPointerSimple.currentProperties.toolType =
3575 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3576 } else {
3577 mPointerVelocityControl.reset();
3578
3579 down = false;
3580 hovering = false;
3581 }
3582
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003583 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003584}
3585
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003586std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3587 uint32_t policyFlags) {
3588 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003589
3590 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003591
3592 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003593}
3594
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003595std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3596 uint32_t policyFlags, bool down,
3597 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003598 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3599 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003600 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003601 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003602
3603 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003604 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003605 mPointerController->clearSpots();
3606 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003607 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003608 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003609 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003610 }
Garfield Tan9514d782020-11-10 16:37:23 -08003611 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003612
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003613 float xCursorPosition, yCursorPosition;
3614 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003615
3616 if (mPointerSimple.down && !down) {
3617 mPointerSimple.down = false;
3618
3619 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003620 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3621 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3622 0, metaState, mLastRawState.buttonState,
3623 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3624 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3625 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3626 yCursorPosition, mPointerSimple.downTime,
3627 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003628 }
3629
3630 if (mPointerSimple.hovering && !hovering) {
3631 mPointerSimple.hovering = false;
3632
3633 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003634 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3635 mSource, displayId, policyFlags,
3636 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3637 mLastRawState.buttonState, MotionClassification::NONE,
3638 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3639 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3640 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3641 yCursorPosition, mPointerSimple.downTime,
3642 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003643 }
3644
3645 if (down) {
3646 if (!mPointerSimple.down) {
3647 mPointerSimple.down = true;
3648 mPointerSimple.downTime = when;
3649
3650 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003651 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3652 mSource, displayId, policyFlags,
3653 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3654 mCurrentRawState.buttonState, MotionClassification::NONE,
3655 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3656 &mPointerSimple.currentProperties,
3657 &mPointerSimple.currentCoords, mOrientedXPrecision,
3658 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3659 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003660 }
3661
3662 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003663 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3664 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3665 0, 0, metaState, mCurrentRawState.buttonState,
3666 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3667 &mPointerSimple.currentProperties,
3668 &mPointerSimple.currentCoords, mOrientedXPrecision,
3669 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3670 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003671 }
3672
3673 if (hovering) {
3674 if (!mPointerSimple.hovering) {
3675 mPointerSimple.hovering = true;
3676
3677 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003678 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3679 mSource, displayId, policyFlags,
3680 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3681 mCurrentRawState.buttonState, MotionClassification::NONE,
3682 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3683 &mPointerSimple.currentProperties,
3684 &mPointerSimple.currentCoords, mOrientedXPrecision,
3685 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3686 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003687 }
3688
3689 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003690 out.push_back(
3691 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3692 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3693 metaState, mCurrentRawState.buttonState,
3694 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3695 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3696 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3697 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003698 }
3699
3700 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3701 float vscroll = mCurrentRawState.rawVScroll;
3702 float hscroll = mCurrentRawState.rawHScroll;
3703 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3704 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3705
3706 // Send scroll.
3707 PointerCoords pointerCoords;
3708 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3709 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3710 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3711
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003712 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3713 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3714 0, 0, metaState, mCurrentRawState.buttonState,
3715 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3716 &mPointerSimple.currentProperties, &pointerCoords,
3717 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3718 yCursorPosition, mPointerSimple.downTime,
3719 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003720 }
3721
3722 // Save state.
3723 if (down || hovering) {
3724 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3725 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003726 mPointerSimple.displayId = displayId;
3727 mPointerSimple.source = mSource;
3728 mPointerSimple.lastCursorX = xCursorPosition;
3729 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003730 } else {
3731 mPointerSimple.reset();
3732 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003733 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003734}
3735
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003736std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3737 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003738 std::list<NotifyArgs> out;
3739 if (mPointerSimple.down || mPointerSimple.hovering) {
3740 int32_t metaState = getContext()->getGlobalMetaState();
3741 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3742 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3743 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3744 metaState, mLastRawState.buttonState,
3745 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3746 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3747 mOrientedXPrecision, mOrientedYPrecision,
3748 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3749 mPointerSimple.downTime,
3750 /* videoFrames */ {}));
3751 if (mPointerController != nullptr) {
3752 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3753 }
3754 }
3755 mPointerSimple.reset();
3756 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003757}
3758
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003759NotifyMotionArgs TouchInputMapper::dispatchMotion(
3760 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3761 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003762 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3763 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003764 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003765 PointerCoords pointerCoords[MAX_POINTERS];
3766 PointerProperties pointerProperties[MAX_POINTERS];
3767 uint32_t pointerCount = 0;
3768 while (!idBits.isEmpty()) {
3769 uint32_t id = idBits.clearFirstMarkedBit();
3770 uint32_t index = idToIndex[id];
3771 pointerProperties[pointerCount].copyFrom(properties[index]);
3772 pointerCoords[pointerCount].copyFrom(coords[index]);
3773
3774 if (changedId >= 0 && id == uint32_t(changedId)) {
3775 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3776 }
3777
3778 pointerCount += 1;
3779 }
3780
3781 ALOG_ASSERT(pointerCount != 0);
3782
3783 if (changedId >= 0 && pointerCount == 1) {
3784 // Replace initial down and final up action.
3785 // We can compare the action without masking off the changed pointer index
3786 // because we know the index is 0.
3787 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3788 action = AMOTION_EVENT_ACTION_DOWN;
3789 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003790 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3791 action = AMOTION_EVENT_ACTION_CANCEL;
3792 } else {
3793 action = AMOTION_EVENT_ACTION_UP;
3794 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003795 } else {
3796 // Can't happen.
3797 ALOG_ASSERT(false);
3798 }
3799 }
3800 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3801 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003802 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003803 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003804 }
3805 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3806 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003807 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003808 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003809 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003810 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3811 policyFlags, action, actionButton, flags, metaState, buttonState,
3812 classification, edgeFlags, pointerCount, pointerProperties,
3813 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3814 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003815}
3816
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003817std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3818 std::list<NotifyArgs> out;
3819 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3820 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3821 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003822}
3823
Prabir Pradhan1728b212021-10-19 16:00:03 -07003824bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003825 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3826 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3827
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003828 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003829 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00003830 isPointInRect(mPhysicalFrameInDisplay, xScaled, yScaled);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003831}
3832
3833const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3834 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003835 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3836 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3837 "left=%d, top=%d, right=%d, bottom=%d",
3838 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3839 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003840
3841 if (virtualKey.isHit(x, y)) {
3842 return &virtualKey;
3843 }
3844 }
3845
3846 return nullptr;
3847}
3848
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003849void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3850 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3851 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003852
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003853 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003854
3855 if (currentPointerCount == 0) {
3856 // No pointers to assign.
3857 return;
3858 }
3859
3860 if (lastPointerCount == 0) {
3861 // All pointers are new.
3862 for (uint32_t i = 0; i < currentPointerCount; i++) {
3863 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003864 current.rawPointerData.pointers[i].id = id;
3865 current.rawPointerData.idToIndex[id] = i;
3866 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003867 }
3868 return;
3869 }
3870
3871 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003872 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003873 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003874 uint32_t id = last.rawPointerData.pointers[0].id;
3875 current.rawPointerData.pointers[0].id = id;
3876 current.rawPointerData.idToIndex[id] = 0;
3877 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003878 return;
3879 }
3880
3881 // General case.
3882 // We build a heap of squared euclidean distances between current and last pointers
3883 // associated with the current and last pointer indices. Then, we find the best
3884 // match (by distance) for each current pointer.
3885 // The pointers must have the same tool type but it is possible for them to
3886 // transition from hovering to touching or vice-versa while retaining the same id.
3887 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3888
3889 uint32_t heapSize = 0;
3890 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3891 currentPointerIndex++) {
3892 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3893 lastPointerIndex++) {
3894 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003895 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003896 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003897 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003898 if (currentPointer.toolType == lastPointer.toolType) {
3899 int64_t deltaX = currentPointer.x - lastPointer.x;
3900 int64_t deltaY = currentPointer.y - lastPointer.y;
3901
3902 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3903
3904 // Insert new element into the heap (sift up).
3905 heap[heapSize].currentPointerIndex = currentPointerIndex;
3906 heap[heapSize].lastPointerIndex = lastPointerIndex;
3907 heap[heapSize].distance = distance;
3908 heapSize += 1;
3909 }
3910 }
3911 }
3912
3913 // Heapify
3914 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3915 startIndex -= 1;
3916 for (uint32_t parentIndex = startIndex;;) {
3917 uint32_t childIndex = parentIndex * 2 + 1;
3918 if (childIndex >= heapSize) {
3919 break;
3920 }
3921
3922 if (childIndex + 1 < heapSize &&
3923 heap[childIndex + 1].distance < heap[childIndex].distance) {
3924 childIndex += 1;
3925 }
3926
3927 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3928 break;
3929 }
3930
3931 swap(heap[parentIndex], heap[childIndex]);
3932 parentIndex = childIndex;
3933 }
3934 }
3935
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003936 if (DEBUG_POINTER_ASSIGNMENT) {
3937 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3938 for (size_t i = 0; i < heapSize; i++) {
3939 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3940 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3941 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003942 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003943
3944 // Pull matches out by increasing order of distance.
3945 // To avoid reassigning pointers that have already been matched, the loop keeps track
3946 // of which last and current pointers have been matched using the matchedXXXBits variables.
3947 // It also tracks the used pointer id bits.
3948 BitSet32 matchedLastBits(0);
3949 BitSet32 matchedCurrentBits(0);
3950 BitSet32 usedIdBits(0);
3951 bool first = true;
3952 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3953 while (heapSize > 0) {
3954 if (first) {
3955 // The first time through the loop, we just consume the root element of
3956 // the heap (the one with smallest distance).
3957 first = false;
3958 } else {
3959 // Previous iterations consumed the root element of the heap.
3960 // Pop root element off of the heap (sift down).
3961 heap[0] = heap[heapSize];
3962 for (uint32_t parentIndex = 0;;) {
3963 uint32_t childIndex = parentIndex * 2 + 1;
3964 if (childIndex >= heapSize) {
3965 break;
3966 }
3967
3968 if (childIndex + 1 < heapSize &&
3969 heap[childIndex + 1].distance < heap[childIndex].distance) {
3970 childIndex += 1;
3971 }
3972
3973 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3974 break;
3975 }
3976
3977 swap(heap[parentIndex], heap[childIndex]);
3978 parentIndex = childIndex;
3979 }
3980
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003981 if (DEBUG_POINTER_ASSIGNMENT) {
3982 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3983 for (size_t j = 0; j < heapSize; j++) {
3984 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3985 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3986 heap[j].distance);
3987 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003988 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003989 }
3990
3991 heapSize -= 1;
3992
3993 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3994 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3995
3996 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3997 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3998
3999 matchedCurrentBits.markBit(currentPointerIndex);
4000 matchedLastBits.markBit(lastPointerIndex);
4001
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004002 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4003 current.rawPointerData.pointers[currentPointerIndex].id = id;
4004 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4005 current.rawPointerData.markIdBit(id,
4006 current.rawPointerData.isHovering(
4007 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004008 usedIdBits.markBit(id);
4009
Harry Cutts45483602022-08-24 14:36:48 +00004010 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4011 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4012 ", distance=%" PRIu64,
4013 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004014 break;
4015 }
4016 }
4017
4018 // Assign fresh ids to pointers that were not matched in the process.
4019 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4020 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4021 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4022
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004023 current.rawPointerData.pointers[currentPointerIndex].id = id;
4024 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4025 current.rawPointerData.markIdBit(id,
4026 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004027
Harry Cutts45483602022-08-24 14:36:48 +00004028 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4029 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4030 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004031 }
4032}
4033
4034int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4035 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4036 return AKEY_STATE_VIRTUAL;
4037 }
4038
4039 for (const VirtualKey& virtualKey : mVirtualKeys) {
4040 if (virtualKey.keyCode == keyCode) {
4041 return AKEY_STATE_UP;
4042 }
4043 }
4044
4045 return AKEY_STATE_UNKNOWN;
4046}
4047
4048int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4049 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4050 return AKEY_STATE_VIRTUAL;
4051 }
4052
4053 for (const VirtualKey& virtualKey : mVirtualKeys) {
4054 if (virtualKey.scanCode == scanCode) {
4055 return AKEY_STATE_UP;
4056 }
4057 }
4058
4059 return AKEY_STATE_UNKNOWN;
4060}
4061
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004062bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4063 const std::vector<int32_t>& keyCodes,
4064 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004065 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004066 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004067 if (virtualKey.keyCode == keyCodes[i]) {
4068 outFlags[i] = 1;
4069 }
4070 }
4071 }
4072
4073 return true;
4074}
4075
4076std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4077 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004078 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004079 return std::make_optional(mPointerController->getDisplayId());
4080 } else {
4081 return std::make_optional(mViewport.displayId);
4082 }
4083 }
4084 return std::nullopt;
4085}
4086
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004087} // namespace android