blob: 66691f83c0a82fcc442ff711fce407db42625dd6 [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Michael Wright227c5542020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wright227c5542020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
21#include "TouchInputMapper.h"
22
Dominik Laskowski75788452021-02-09 18:51:25 -080023#include <ftl/enum.h>
Prabir Pradhan8d9ba912022-11-11 22:26:33 +000024#include <input/PrintTools.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080025
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070026#include "CursorButtonAccumulator.h"
27#include "CursorScrollAccumulator.h"
28#include "TouchButtonAccumulator.h"
29#include "TouchCursorInputMapperCommon.h"
Michael Wrighta9cf4192022-12-01 23:46:39 +000030#include "ui/Rotation.h"
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070031
32namespace android {
33
34// --- Constants ---
35
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070036// Artificial latency on synthetic events created from stylus data without corresponding touch
37// data.
38static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
39
HQ Liue6983c72022-04-19 22:14:56 +000040// Minimum width between two pointers to determine a gesture as freeform gesture in mm
41static const float MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER = 30;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070042// --- Static Definitions ---
43
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +000044static const DisplayViewport kUninitializedViewport;
45
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000046static std::string toString(const Rect& rect) {
47 return base::StringPrintf("Rect{%d, %d, %d, %d}", rect.left, rect.top, rect.right, rect.bottom);
48}
49
50static std::string toString(const ui::Size& size) {
51 return base::StringPrintf("%dx%d", size.width, size.height);
52}
53
Prabir Pradhan675f25a2022-11-10 22:04:07 +000054static bool isPointInRect(const Rect& rect, vec2 p) {
55 return p.x >= rect.left && p.x < rect.right && p.y >= rect.top && p.y < rect.bottom;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000056}
57
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070058template <typename T>
59inline static void swap(T& a, T& b) {
60 T temp = a;
61 a = b;
62 b = temp;
63}
64
65static float calculateCommonVector(float a, float b) {
66 if (a > 0 && b > 0) {
67 return a < b ? a : b;
68 } else if (a < 0 && b < 0) {
69 return a > b ? a : b;
70 } else {
71 return 0;
72 }
73}
74
75inline static float distance(float x1, float y1, float x2, float y2) {
76 return hypotf(x1 - x2, y1 - y2);
77}
78
79inline static int32_t signExtendNybble(int32_t value) {
80 return value >= 8 ? value - 16 : value;
81}
82
Prabir Pradhan675f25a2022-11-10 22:04:07 +000083static ui::Size getNaturalDisplaySize(const DisplayViewport& viewport) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000084 ui::Size rotatedDisplaySize{viewport.deviceWidth, viewport.deviceHeight};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +000085 if (viewport.orientation == ui::ROTATION_90 || viewport.orientation == ui::ROTATION_270) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000086 std::swap(rotatedDisplaySize.width, rotatedDisplaySize.height);
87 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +000088 return rotatedDisplaySize;
Prabir Pradhan2d613f42022-11-10 20:22:06 +000089}
90
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070091// --- RawPointerData ---
92
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070093void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
94 float x = 0, y = 0;
95 uint32_t count = touchingIdBits.count();
96 if (count) {
97 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
98 uint32_t id = idBits.clearFirstMarkedBit();
99 const Pointer& pointer = pointerForId(id);
100 x += pointer.x;
101 y += pointer.y;
102 }
103 x /= count;
104 y /= count;
105 }
106 *outX = x;
107 *outY = y;
108}
109
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700110// --- TouchInputMapper ---
111
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800112TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
113 : InputMapper(deviceContext),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000114 mTouchButtonAccumulator(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700115 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100116 mDeviceMode(DeviceMode::DISABLED),
Michael Wrighta9cf4192022-12-01 23:46:39 +0000117 mInputDeviceOrientation(ui::ROTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700118
119TouchInputMapper::~TouchInputMapper() {}
120
Philip Junker4af3b3d2021-12-14 10:36:55 +0100121uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700122 return mSource;
123}
124
125void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
126 InputMapper::populateDeviceInfo(info);
127
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000128 if (mDeviceMode == DeviceMode::DISABLED) {
129 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700130 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000131
132 info->addMotionRange(mOrientedRanges.x);
133 info->addMotionRange(mOrientedRanges.y);
134 info->addMotionRange(mOrientedRanges.pressure);
135
136 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
137 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
138 //
139 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
140 // motion, i.e. the hardware dimensions, as the finger could move completely across the
141 // touchpad in one sample cycle.
142 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
143 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
144 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
145 x.resolution);
146 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
147 y.resolution);
148 }
149
150 if (mOrientedRanges.size) {
151 info->addMotionRange(*mOrientedRanges.size);
152 }
153
154 if (mOrientedRanges.touchMajor) {
155 info->addMotionRange(*mOrientedRanges.touchMajor);
156 info->addMotionRange(*mOrientedRanges.touchMinor);
157 }
158
159 if (mOrientedRanges.toolMajor) {
160 info->addMotionRange(*mOrientedRanges.toolMajor);
161 info->addMotionRange(*mOrientedRanges.toolMinor);
162 }
163
164 if (mOrientedRanges.orientation) {
165 info->addMotionRange(*mOrientedRanges.orientation);
166 }
167
168 if (mOrientedRanges.distance) {
169 info->addMotionRange(*mOrientedRanges.distance);
170 }
171
172 if (mOrientedRanges.tilt) {
173 info->addMotionRange(*mOrientedRanges.tilt);
174 }
175
176 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
177 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
178 }
179 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
180 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
181 }
182 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
183 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
184 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
185 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat, x.fuzz,
186 x.resolution);
187 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat, y.fuzz,
188 y.resolution);
189 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat, x.fuzz,
190 x.resolution);
191 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat, y.fuzz,
192 y.resolution);
193 }
194 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000195 info->setSupportsUsi(mParameters.supportsUsi);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700196}
197
198void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700199 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800200 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700201 dumpParameters(dump);
202 dumpVirtualKeys(dump);
203 dumpRawPointerAxes(dump);
204 dumpCalibration(dump);
205 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700206 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700207
208 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000209 mRawToDisplay.dump(dump, "RawToDisplay Transform:", INDENT4);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700210 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
211 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
212 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
213 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
214 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
215 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
216 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
217 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
218 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
219 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
220 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
221 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
222 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
223 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
224
225 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
226 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
227 mLastRawState.rawPointerData.pointerCount);
228 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
229 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
230 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
231 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
232 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
233 "toolType=%d, isHovering=%s\n",
234 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
235 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
236 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
237 pointer.distance, pointer.toolType, toString(pointer.isHovering));
238 }
239
240 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
241 mLastCookedState.buttonState);
242 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
243 mLastCookedState.cookedPointerData.pointerCount);
244 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
245 const PointerProperties& pointerProperties =
246 mLastCookedState.cookedPointerData.pointerProperties[i];
247 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000248 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
249 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
250 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700251 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
252 "toolType=%d, isHovering=%s\n",
253 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000254 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
255 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700256 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
257 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
258 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
259 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
260 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
261 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
262 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
263 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
264 pointerProperties.toolType,
265 toString(mLastCookedState.cookedPointerData.isHovering(i)));
266 }
267
268 dump += INDENT3 "Stylus Fusion:\n";
269 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
270 toString(mExternalStylusConnected));
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000271 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
272 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700273 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
274 mExternalStylusFusionTimeout);
Prabir Pradhan124ea442022-10-28 20:27:44 +0000275 dump += StringPrintf(INDENT4 " External Stylus Buttons Applied: 0x%08x",
276 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700277 dump += INDENT3 "External Stylus State:\n";
278 dumpStylusState(dump, mExternalStylusState);
279
Michael Wright227c5542020-07-02 18:30:52 +0100280 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700281 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
282 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
283 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
284 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
285 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
286 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
287 }
288}
289
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700290std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
291 const InputReaderConfiguration* config,
292 uint32_t changes) {
293 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700294
295 mConfig = *config;
296
297 if (!changes) { // first time only
298 // Configure basic parameters.
299 configureParameters();
300
301 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800302 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000303 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700304
305 // Configure absolute axis information.
306 configureRawPointerAxes();
307
308 // Prepare input device calibration.
309 parseCalibration();
310 resolveCalibration();
311 }
312
313 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
314 // Update location calibration to reflect current settings
315 updateAffineTransformation();
316 }
317
318 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
319 // Update pointer speed.
320 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
321 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
322 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
323 }
324
325 bool resetNeeded = false;
326 if (!changes ||
327 (changes &
328 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800329 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700330 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
331 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
332 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700333 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700334 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700335 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700336 }
337
338 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700339 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000340
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700341 // Send reset, unless this is the first time the device has been configured,
342 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000343 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700344 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700345 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700346}
347
348void TouchInputMapper::resolveExternalStylusPresence() {
349 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800350 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700351 mExternalStylusConnected = !devices.empty();
352
353 if (!mExternalStylusConnected) {
354 resetExternalStylus();
355 }
356}
357
358void TouchInputMapper::configureParameters() {
359 // Use the pointer presentation mode for devices that do not support distinct
360 // multitouch. The spot-based presentation relies on being able to accurately
361 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800362 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100363 ? Parameters::GestureMode::SINGLE_TOUCH
364 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700365
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700366 std::string gestureModeString;
367 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800368 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700369 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100370 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700371 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100372 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700373 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700374 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700375 }
376 }
377
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000378 configureDeviceType();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700379
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800380 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700381
Michael Wright227c5542020-07-02 18:30:52 +0100382 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700383 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800384 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700385
Michael Wrighta9cf4192022-12-01 23:46:39 +0000386 mParameters.orientation = ui::ROTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700387 std::string orientationString;
388 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700389 orientationString)) {
390 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
391 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
392 } else if (orientationString == "ORIENTATION_90") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000393 mParameters.orientation = ui::ROTATION_90;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700394 } else if (orientationString == "ORIENTATION_180") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000395 mParameters.orientation = ui::ROTATION_180;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700396 } else if (orientationString == "ORIENTATION_270") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000397 mParameters.orientation = ui::ROTATION_270;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700398 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700399 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700400 }
401 }
402
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700403 mParameters.hasAssociatedDisplay = false;
404 mParameters.associatedDisplayIsExternal = false;
405 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100406 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000407 mParameters.deviceType == Parameters::DeviceType::POINTER ||
408 (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
409 getDeviceContext().getAssociatedViewport())) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700410 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100411 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800412 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700413 std::string uniqueDisplayId;
414 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800415 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700416 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
417 }
418 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800419 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700420 mParameters.hasAssociatedDisplay = true;
421 }
422
423 // Initial downs on external touch devices should wake the device.
424 // Normally we don't do this for internal touch screens to prevent them from waking
425 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800426 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700427 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000428
429 mParameters.supportsUsi = false;
430 getDeviceContext().getConfiguration().tryGetProperty("touch.supportsUsi",
431 mParameters.supportsUsi);
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700432
433 mParameters.enableForInactiveViewport = false;
434 getDeviceContext().getConfiguration().tryGetProperty("touch.enableForInactiveViewport",
435 mParameters.enableForInactiveViewport);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700436}
437
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000438void TouchInputMapper::configureDeviceType() {
439 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
440 // The device is a touch screen.
441 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
442 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
443 // The device is a pointing device like a track pad.
444 mParameters.deviceType = Parameters::DeviceType::POINTER;
445 } else {
446 // The device is a touch pad of unknown purpose.
447 mParameters.deviceType = Parameters::DeviceType::POINTER;
448 }
449
450 // Type association takes precedence over the device type found in the idc file.
451 std::string deviceTypeString = getDeviceContext().getDeviceTypeAssociation().value_or("");
452 if (deviceTypeString.empty()) {
453 getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType", deviceTypeString);
454 }
455 if (deviceTypeString == "touchScreen") {
456 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
457 } else if (deviceTypeString == "touchNavigation") {
458 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
459 } else if (deviceTypeString == "pointer") {
460 mParameters.deviceType = Parameters::DeviceType::POINTER;
461 } else if (deviceTypeString != "default" && deviceTypeString != "") {
462 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
463 }
464}
465
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700466void TouchInputMapper::dumpParameters(std::string& dump) {
467 dump += INDENT3 "Parameters:\n";
468
Dominik Laskowski75788452021-02-09 18:51:25 -0800469 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700470
Dominik Laskowski75788452021-02-09 18:51:25 -0800471 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700472
473 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
474 "displayId='%s'\n",
475 toString(mParameters.hasAssociatedDisplay),
476 toString(mParameters.associatedDisplayIsExternal),
477 mParameters.uniqueDisplayId.c_str());
478 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800479 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhan167c2702022-09-14 00:37:24 +0000480 dump += StringPrintf(INDENT4 "SupportsUsi: %s\n", toString(mParameters.supportsUsi));
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700481 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
482 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700483}
484
485void TouchInputMapper::configureRawPointerAxes() {
486 mRawPointerAxes.clear();
487}
488
489void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
490 dump += INDENT3 "Raw Touch Axes:\n";
491 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
492 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
493 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
494 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
495 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
496 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
497 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
498 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
499 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
500 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
501 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
502 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
503 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
504}
505
506bool TouchInputMapper::hasExternalStylus() const {
507 return mExternalStylusConnected;
508}
509
510/**
511 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000512 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800513 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000514 * 3. Get the matching viewport by either unique id in idc file or by the display type
515 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800516 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700517 */
518std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800519 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000520 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800521 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700522 }
523
Christine Franks2a2293c2022-01-18 11:51:16 -0800524 const std::optional<std::string> associatedDisplayUniqueId =
525 getDeviceContext().getAssociatedDisplayUniqueId();
526 if (associatedDisplayUniqueId) {
527 return getDeviceContext().getAssociatedViewport();
528 }
529
Michael Wright227c5542020-07-02 18:30:52 +0100530 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800531 std::optional<DisplayViewport> viewport =
532 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
533 if (viewport) {
534 return viewport;
535 } else {
536 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
537 mConfig.defaultPointerDisplayId);
538 }
539 }
540
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700541 // Check if uniqueDisplayId is specified in idc file.
542 if (!mParameters.uniqueDisplayId.empty()) {
543 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
544 }
545
546 ViewportType viewportTypeToUse;
547 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100548 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700549 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100550 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700551 }
552
553 std::optional<DisplayViewport> viewport =
554 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100555 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700556 ALOGW("Input device %s should be associated with external display, "
557 "fallback to internal one for the external viewport is not found.",
558 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100559 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700560 }
561
562 return viewport;
563 }
564
565 // No associated display, return a non-display viewport.
566 DisplayViewport newViewport;
567 // Raw width and height in the natural orientation.
568 int32_t rawWidth = mRawPointerAxes.getRawWidth();
569 int32_t rawHeight = mRawPointerAxes.getRawHeight();
570 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
571 return std::make_optional(newViewport);
572}
573
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800574int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
575 if (resolution < 0) {
576 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
577 getDeviceName().c_str());
578 return 0;
579 }
580 return resolution;
581}
582
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800583void TouchInputMapper::initializeSizeRanges() {
584 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
585 mSizeScale = 0.0f;
586 return;
587 }
588
589 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000590 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800591
592 // Size factors.
593 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
594 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
595 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
596 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
597 } else {
598 mSizeScale = 0.0f;
599 }
600
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700601 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
602 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
603 .source = mSource,
604 .min = 0,
605 .max = diagonalSize,
606 .flat = 0,
607 .fuzz = 0,
608 .resolution = 0,
609 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800610
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800611 if (mRawPointerAxes.touchMajor.valid) {
612 mRawPointerAxes.touchMajor.resolution =
613 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700614 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800615 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800616
617 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700618 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800619 if (mRawPointerAxes.touchMinor.valid) {
620 mRawPointerAxes.touchMinor.resolution =
621 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700622 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800623 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800624
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700625 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
626 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
627 .source = mSource,
628 .min = 0,
629 .max = diagonalSize,
630 .flat = 0,
631 .fuzz = 0,
632 .resolution = 0,
633 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800634 if (mRawPointerAxes.toolMajor.valid) {
635 mRawPointerAxes.toolMajor.resolution =
636 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700637 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800638 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800639
640 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700641 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800642 if (mRawPointerAxes.toolMinor.valid) {
643 mRawPointerAxes.toolMinor.resolution =
644 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700645 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800646 }
647
648 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700649 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
650 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
651 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
652 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800653 } else {
654 // Support for other calibrations can be added here.
655 ALOGW("%s calibration is not supported for size ranges at the moment. "
656 "Using raw resolution instead",
657 ftl::enum_string(mCalibration.sizeCalibration).c_str());
658 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800659
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700660 mOrientedRanges.size = InputDeviceInfo::MotionRange{
661 .axis = AMOTION_EVENT_AXIS_SIZE,
662 .source = mSource,
663 .min = 0,
664 .max = 1.0,
665 .flat = 0,
666 .fuzz = 0,
667 .resolution = 0,
668 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800669}
670
671void TouchInputMapper::initializeOrientedRanges() {
672 // Configure X and Y factors.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000673 mXScale = float(mDisplayBounds.width) / mRawPointerAxes.getRawWidth();
674 mYScale = float(mDisplayBounds.height) / mRawPointerAxes.getRawHeight();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800675 mXPrecision = 1.0f / mXScale;
676 mYPrecision = 1.0f / mYScale;
677
678 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
679 mOrientedRanges.x.source = mSource;
680 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
681 mOrientedRanges.y.source = mSource;
682
683 // Scale factor for terms that are not oriented in a particular axis.
684 // If the pixels are square then xScale == yScale otherwise we fake it
685 // by choosing an average.
686 mGeometricScale = avg(mXScale, mYScale);
687
688 initializeSizeRanges();
689
690 // Pressure factors.
691 mPressureScale = 0;
692 float pressureMax = 1.0;
693 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
694 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700695 if (mCalibration.pressureScale) {
696 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800697 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
698 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
699 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
700 }
701 }
702
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700703 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
704 .axis = AMOTION_EVENT_AXIS_PRESSURE,
705 .source = mSource,
706 .min = 0,
707 .max = pressureMax,
708 .flat = 0,
709 .fuzz = 0,
710 .resolution = 0,
711 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800712
713 // Tilt
714 mTiltXCenter = 0;
715 mTiltXScale = 0;
716 mTiltYCenter = 0;
717 mTiltYScale = 0;
718 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
719 if (mHaveTilt) {
720 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
721 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
722 mTiltXScale = M_PI / 180;
723 mTiltYScale = M_PI / 180;
724
725 if (mRawPointerAxes.tiltX.resolution) {
726 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
727 }
728 if (mRawPointerAxes.tiltY.resolution) {
729 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
730 }
731
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700732 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
733 .axis = AMOTION_EVENT_AXIS_TILT,
734 .source = mSource,
735 .min = 0,
736 .max = M_PI_2,
737 .flat = 0,
738 .fuzz = 0,
739 .resolution = 0,
740 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800741 }
742
743 // Orientation
744 mOrientationScale = 0;
745 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700746 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
747 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
748 .source = mSource,
749 .min = -M_PI,
750 .max = M_PI,
751 .flat = 0,
752 .fuzz = 0,
753 .resolution = 0,
754 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800755
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800756 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
757 if (mCalibration.orientationCalibration ==
758 Calibration::OrientationCalibration::INTERPOLATED) {
759 if (mRawPointerAxes.orientation.valid) {
760 if (mRawPointerAxes.orientation.maxValue > 0) {
761 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
762 } else if (mRawPointerAxes.orientation.minValue < 0) {
763 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
764 } else {
765 mOrientationScale = 0;
766 }
767 }
768 }
769
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700770 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
771 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
772 .source = mSource,
773 .min = -M_PI_2,
774 .max = M_PI_2,
775 .flat = 0,
776 .fuzz = 0,
777 .resolution = 0,
778 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800779 }
780
781 // Distance
782 mDistanceScale = 0;
783 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
784 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700785 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800786 }
787
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700788 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800789
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700790 .axis = AMOTION_EVENT_AXIS_DISTANCE,
791 .source = mSource,
792 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
793 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
794 .flat = 0,
795 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
796 .resolution = 0,
797 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800798 }
799
800 // Compute oriented precision, scales and ranges.
801 // Note that the maximum value reported is an inclusive maximum value so it is one
802 // unit less than the total width or height of the display.
803 switch (mInputDeviceOrientation) {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000804 case ui::ROTATION_90:
805 case ui::ROTATION_270:
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800806 mOrientedXPrecision = mYPrecision;
807 mOrientedYPrecision = mXPrecision;
808
809 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000810 mOrientedRanges.x.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800811 mOrientedRanges.x.flat = 0;
812 mOrientedRanges.x.fuzz = 0;
813 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
814
815 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000816 mOrientedRanges.y.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800817 mOrientedRanges.y.flat = 0;
818 mOrientedRanges.y.fuzz = 0;
819 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
820 break;
821
822 default:
823 mOrientedXPrecision = mXPrecision;
824 mOrientedYPrecision = mYPrecision;
825
826 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000827 mOrientedRanges.x.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800828 mOrientedRanges.x.flat = 0;
829 mOrientedRanges.x.fuzz = 0;
830 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
831
832 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000833 mOrientedRanges.y.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800834 mOrientedRanges.y.flat = 0;
835 mOrientedRanges.y.fuzz = 0;
836 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
837 break;
838 }
839}
840
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000841void TouchInputMapper::computeInputTransforms() {
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000842 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
843
844 ui::Size rotatedRawSize = rawSize;
845 if (mInputDeviceOrientation == ui::ROTATION_270 || mInputDeviceOrientation == ui::ROTATION_90) {
846 std::swap(rotatedRawSize.width, rotatedRawSize.height);
847 }
848
849 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
850 ui::Transform undoRawOffset;
851 undoRawOffset.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
852
853 // Step 2: Rotate the raw coordinates to the expected orientation.
854 ui::Transform rotate;
855 // When rotating raw coordinates, the raw size will be used as an offset.
856 // Account for the extra unit added to the raw range when the raw size was calculated.
857 rotate.set(ui::Transform::toRotationFlags(-mInputDeviceOrientation), rotatedRawSize.width - 1,
858 rotatedRawSize.height - 1);
859
860 // Step 3: Scale the raw coordinates to the display space.
861 ui::Transform scaleToDisplay;
862 const float xScale = static_cast<float>(mDisplayBounds.width) / rotatedRawSize.width;
863 const float yScale = static_cast<float>(mDisplayBounds.height) / rotatedRawSize.height;
864 scaleToDisplay.set(xScale, 0, 0, yScale);
865
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000866 mRawToDisplay = (scaleToDisplay * (rotate * undoRawOffset));
867
868 // Calculate the transform that takes raw coordinates to the rotated display space.
869 ui::Transform displayToRotatedDisplay;
870 displayToRotatedDisplay.set(ui::Transform::toRotationFlags(-mViewport.orientation),
871 mViewport.deviceWidth, mViewport.deviceHeight);
872 mRawToRotatedDisplay = displayToRotatedDisplay * mRawToDisplay;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000873}
874
Prabir Pradhan1728b212021-10-19 16:00:03 -0700875void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000876 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700877
878 resolveExternalStylusPresence();
879
880 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100881 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000882 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700883 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100884 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700885 if (hasStylus()) {
886 mSource |= AINPUT_SOURCE_STYLUS;
Harry Cutts16a24cc2022-10-26 15:22:19 +0000887 } else {
888 mSource |= AINPUT_SOURCE_TOUCHPAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700889 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800890 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700891 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100892 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700893 if (hasStylus()) {
894 mSource |= AINPUT_SOURCE_STYLUS;
895 }
896 if (hasExternalStylus()) {
897 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
898 }
Michael Wright227c5542020-07-02 18:30:52 +0100899 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700900 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100901 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700902 } else {
903 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100904 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700905 }
906
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000907 const std::optional<DisplayViewport> newViewportOpt = findViewport();
908
909 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700910 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
911 ALOGW("Touch device '%s' did not report support for X or Y axis! "
912 "The device will be inoperable.",
913 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100914 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000915 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700916 ALOGI("Touch device '%s' could not query the properties of its associated "
917 "display. The device will be inoperable until the display size "
918 "becomes available.",
919 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100920 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700921 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000922 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
923 getDeviceName().c_str(), getDeviceId());
924 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000925 }
926
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700927 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000928 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000929 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
930 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
931 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
932 const float rawMeanResolution =
933 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700934
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000935 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
936 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700937 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700938 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000939 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
940 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
941 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700942
Michael Wright227c5542020-07-02 18:30:52 +0100943 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000944 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700945
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000946 mDisplayBounds = getNaturalDisplaySize(mViewport);
947 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
948 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700949
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000950 // InputReader works in the un-rotated display coordinate space, so we don't need to do
951 // anything if the device is already orientation-aware. If the device is not
952 // orientation-aware, then we need to apply the inverse rotation of the display so that
953 // when the display rotation is applied later as a part of the per-window transform, we
954 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700955 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +0000956 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000957 : getInverseRotation(mViewport.orientation);
958 // For orientation-aware devices that work in the un-rotated coordinate space, the
959 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000960 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000961 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700962
963 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +0000964 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000965 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700966 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000967 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000968 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +0000969 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000970 mRawToDisplay.reset();
971 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000972 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700973 }
974 }
975
976 // If moving between pointer modes, need to reset some state.
977 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
978 if (deviceModeChanged) {
979 mOrientedRanges.clear();
980 }
981
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800982 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
983 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100984 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800985 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000986 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
987 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800988 if (mPointerController == nullptr) {
989 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700990 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000991 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800992 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
993 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700994 } else {
lilinnandef700b2022-06-17 19:32:01 +0800995 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
996 !mConfig.showTouches) {
997 mPointerController->clearSpots();
998 }
Michael Wright17db18e2020-06-26 20:51:44 +0100999 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001000 }
1001
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001002 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001003 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001004 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001005 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001006 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001007
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001008 configureVirtualKeys();
1009
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001010 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001011
1012 // Location
1013 updateAffineTransformation();
1014
Michael Wright227c5542020-07-02 18:30:52 +01001015 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001016 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001017 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1018 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001019
1020 // Scale movements such that one whole swipe of the touch pad covers a
1021 // given area relative to the diagonal size of the display when no acceleration
1022 // is applied.
1023 // Assume that the touch pad has a square aspect ratio such that movements in
1024 // X and Y of the same number of raw units cover the same physical distance.
1025 mPointerXMovementScale =
1026 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1027 mPointerYMovementScale = mPointerXMovementScale;
1028
1029 // Scale zooms to cover a smaller range of the display than movements do.
1030 // This value determines the area around the pointer that is affected by freeform
1031 // pointer gestures.
1032 mPointerXZoomScale =
1033 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1034 mPointerYZoomScale = mPointerXZoomScale;
1035
HQ Liue6983c72022-04-19 22:14:56 +00001036 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1037 // axis is non positive value.
1038 const float minFreeformGestureWidth =
1039 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1040
1041 mPointerGestureMaxSwipeWidth =
1042 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1043 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001044 }
1045
1046 // Inform the dispatcher about the changes.
1047 *outResetNeeded = true;
1048 bumpGeneration();
1049 }
1050}
1051
Prabir Pradhan1728b212021-10-19 16:00:03 -07001052void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001053 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001054 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001055 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1056 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001057 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001058}
1059
1060void TouchInputMapper::configureVirtualKeys() {
1061 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001062 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001063
1064 mVirtualKeys.clear();
1065
1066 if (virtualKeyDefinitions.size() == 0) {
1067 return;
1068 }
1069
1070 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1071 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1072 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1073 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1074
1075 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1076 VirtualKey virtualKey;
1077
1078 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1079 int32_t keyCode;
1080 int32_t dummyKeyMetaState;
1081 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001082 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1083 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001084 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1085 continue; // drop the key
1086 }
1087
1088 virtualKey.keyCode = keyCode;
1089 virtualKey.flags = flags;
1090
1091 // convert the key definition's display coordinates into touch coordinates for a hit box
1092 int32_t halfWidth = virtualKeyDefinition.width / 2;
1093 int32_t halfHeight = virtualKeyDefinition.height / 2;
1094
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001095 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1096 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001097 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001098 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1099 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001100 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001101 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1102 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001103 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001104 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1105 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001106 touchScreenTop;
1107 mVirtualKeys.push_back(virtualKey);
1108 }
1109}
1110
1111void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1112 if (!mVirtualKeys.empty()) {
1113 dump += INDENT3 "Virtual Keys:\n";
1114
1115 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1116 const VirtualKey& virtualKey = mVirtualKeys[i];
1117 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1118 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1119 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1120 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1121 }
1122 }
1123}
1124
1125void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001126 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001127 Calibration& out = mCalibration;
1128
1129 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001130 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001131 std::string sizeCalibrationString;
1132 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001133 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001134 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001135 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001136 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001137 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001138 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001140 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001141 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001142 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001143 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001144 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 }
1146 }
1147
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001148 float sizeScale;
1149
1150 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1151 out.sizeScale = sizeScale;
1152 }
1153 float sizeBias;
1154 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1155 out.sizeBias = sizeBias;
1156 }
1157 bool sizeIsSummed;
1158 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1159 out.sizeIsSummed = sizeIsSummed;
1160 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001161
1162 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001163 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001164 std::string pressureCalibrationString;
1165 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001166 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001167 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001168 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001169 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 } else if (pressureCalibrationString != "default") {
1173 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001174 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001175 }
1176 }
1177
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001178 float pressureScale;
1179 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1180 out.pressureScale = pressureScale;
1181 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001182
1183 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001184 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001185 std::string orientationCalibrationString;
1186 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001187 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001188 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001189 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001190 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001191 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001192 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193 } else if (orientationCalibrationString != "default") {
1194 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001195 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001196 }
1197 }
1198
1199 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001201 std::string distanceCalibrationString;
1202 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001203 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001204 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001206 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001207 } else if (distanceCalibrationString != "default") {
1208 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001209 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001210 }
1211 }
1212
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001213 float distanceScale;
1214 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1215 out.distanceScale = distanceScale;
1216 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001217
Michael Wright227c5542020-07-02 18:30:52 +01001218 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001219 std::string coverageCalibrationString;
1220 if (in.tryGetProperty("touch.coverage.calibration", coverageCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001221 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001222 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001223 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001224 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001225 } else if (coverageCalibrationString != "default") {
1226 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001227 coverageCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001228 }
1229 }
1230}
1231
1232void TouchInputMapper::resolveCalibration() {
1233 // Size
1234 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001235 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1236 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001237 }
1238 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001239 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001240 }
1241
1242 // Pressure
1243 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001244 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1245 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001246 }
1247 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001248 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001249 }
1250
1251 // Orientation
1252 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001253 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1254 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001255 }
1256 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001257 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001258 }
1259
1260 // Distance
1261 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001262 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1263 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001264 }
1265 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001266 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001267 }
1268
1269 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001270 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1271 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001272 }
1273}
1274
1275void TouchInputMapper::dumpCalibration(std::string& dump) {
1276 dump += INDENT3 "Calibration:\n";
1277
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001278 dump += INDENT4 "touch.size.calibration: ";
1279 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001280
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001281 if (mCalibration.sizeScale) {
1282 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001283 }
1284
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001285 if (mCalibration.sizeBias) {
1286 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287 }
1288
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001289 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001290 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001291 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001292 }
1293
1294 // Pressure
1295 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001296 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001297 dump += INDENT4 "touch.pressure.calibration: none\n";
1298 break;
Michael Wright227c5542020-07-02 18:30:52 +01001299 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001300 dump += INDENT4 "touch.pressure.calibration: physical\n";
1301 break;
Michael Wright227c5542020-07-02 18:30:52 +01001302 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001303 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1304 break;
1305 default:
1306 ALOG_ASSERT(false);
1307 }
1308
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001309 if (mCalibration.pressureScale) {
1310 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001311 }
1312
1313 // Orientation
1314 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001315 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001316 dump += INDENT4 "touch.orientation.calibration: none\n";
1317 break;
Michael Wright227c5542020-07-02 18:30:52 +01001318 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001319 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1320 break;
Michael Wright227c5542020-07-02 18:30:52 +01001321 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001322 dump += INDENT4 "touch.orientation.calibration: vector\n";
1323 break;
1324 default:
1325 ALOG_ASSERT(false);
1326 }
1327
1328 // Distance
1329 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001330 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 dump += INDENT4 "touch.distance.calibration: none\n";
1332 break;
Michael Wright227c5542020-07-02 18:30:52 +01001333 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001334 dump += INDENT4 "touch.distance.calibration: scaled\n";
1335 break;
1336 default:
1337 ALOG_ASSERT(false);
1338 }
1339
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001340 if (mCalibration.distanceScale) {
1341 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001342 }
1343
1344 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001345 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001346 dump += INDENT4 "touch.coverage.calibration: none\n";
1347 break;
Michael Wright227c5542020-07-02 18:30:52 +01001348 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001349 dump += INDENT4 "touch.coverage.calibration: box\n";
1350 break;
1351 default:
1352 ALOG_ASSERT(false);
1353 }
1354}
1355
1356void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1357 dump += INDENT3 "Affine Transformation:\n";
1358
1359 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1360 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1361 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1362 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1363 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1364 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1365}
1366
1367void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001368 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001369 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001370}
1371
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001372std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001373 std::list<NotifyArgs> out = cancelTouch(when, when);
1374 updateTouchSpots();
1375
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001376 mCursorButtonAccumulator.reset(getDeviceContext());
1377 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001378 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001379
1380 mPointerVelocityControl.reset();
1381 mWheelXVelocityControl.reset();
1382 mWheelYVelocityControl.reset();
1383
1384 mRawStatesPending.clear();
1385 mCurrentRawState.clear();
1386 mCurrentCookedState.clear();
1387 mLastRawState.clear();
1388 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001389 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001390 mSentHoverEnter = false;
1391 mHavePointerIds = false;
1392 mCurrentMotionAborted = false;
1393 mDownTime = 0;
1394
1395 mCurrentVirtualKey.down = false;
1396
1397 mPointerGesture.reset();
1398 mPointerSimple.reset();
1399 resetExternalStylus();
1400
1401 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001402 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001403 mPointerController->clearSpots();
1404 }
1405
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001406 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001407}
1408
1409void TouchInputMapper::resetExternalStylus() {
1410 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001411 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001412 mExternalStylusFusionTimeout = LLONG_MAX;
1413 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001414 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001415}
1416
1417void TouchInputMapper::clearStylusDataPendingFlags() {
1418 mExternalStylusDataPending = false;
1419 mExternalStylusFusionTimeout = LLONG_MAX;
1420}
1421
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001422std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001423 mCursorButtonAccumulator.process(rawEvent);
1424 mCursorScrollAccumulator.process(rawEvent);
1425 mTouchButtonAccumulator.process(rawEvent);
1426
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001427 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001428 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001429 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001430 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001431 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001432}
1433
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001434std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1435 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001436 if (mDeviceMode == DeviceMode::DISABLED) {
1437 // Only save the last pending state when the device is disabled.
1438 mRawStatesPending.clear();
1439 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001440 // Push a new state.
1441 mRawStatesPending.emplace_back();
1442
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001443 RawState& next = mRawStatesPending.back();
1444 next.clear();
1445 next.when = when;
1446 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001447
1448 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001449 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001450 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1451
1452 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001453 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1454 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001455 mCursorScrollAccumulator.finishSync();
1456
1457 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001458 syncTouch(when, &next);
1459
1460 // The last RawState is the actually second to last, since we just added a new state
1461 const RawState& last =
1462 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001463
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001464 std::tie(next.when, next.readTime) =
1465 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1466 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001467
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001468 // Assign pointer ids.
1469 if (!mHavePointerIds) {
1470 assignPointerIds(last, next);
1471 }
1472
Harry Cutts45483602022-08-24 14:36:48 +00001473 ALOGD_IF(DEBUG_RAW_EVENTS,
1474 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1475 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1476 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1477 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1478 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1479 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001480
Arthur Hung9ad18942021-06-19 02:04:46 +00001481 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1482 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1483 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1484 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1485 next.rawPointerData.hoveringIdBits.value);
1486 }
1487
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001488 out += processRawTouches(false /*timeout*/);
1489 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001490}
1491
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001492std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1493 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001494 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001495 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001496 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001497 }
1498
1499 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1500 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1501 // touching the current state will only observe the events that have been dispatched to the
1502 // rest of the pipeline.
1503 const size_t N = mRawStatesPending.size();
1504 size_t count;
1505 for (count = 0; count < N; count++) {
1506 const RawState& next = mRawStatesPending[count];
1507
1508 // A failure to assign the stylus id means that we're waiting on stylus data
1509 // and so should defer the rest of the pipeline.
1510 if (assignExternalStylusId(next, timeout)) {
1511 break;
1512 }
1513
1514 // All ready to go.
1515 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001516 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001517 if (mCurrentRawState.when < mLastRawState.when) {
1518 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001519 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001520 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001521 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001522 }
1523 if (count != 0) {
1524 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1525 }
1526
1527 if (mExternalStylusDataPending) {
1528 if (timeout) {
1529 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1530 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001531 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001532 ALOGD_IF(DEBUG_STYLUS_FUSION,
1533 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001534 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001535 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001536 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1537 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1538 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1539 }
1540 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001541 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001542}
1543
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001544std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1545 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001546 // Always start with a clean state.
1547 mCurrentCookedState.clear();
1548
1549 // Apply stylus buttons to current raw state.
1550 applyExternalStylusButtonState(when);
1551
1552 // Handle policy on initial down or hover events.
1553 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1554 mCurrentRawState.rawPointerData.pointerCount != 0;
1555
1556 uint32_t policyFlags = 0;
1557 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1558 if (initialDown || buttonsPressed) {
1559 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001560 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001561 getContext()->fadePointer();
1562 }
1563
1564 if (mParameters.wake) {
1565 policyFlags |= POLICY_FLAG_WAKE;
1566 }
1567 }
1568
1569 // Consume raw off-screen touches before cooking pointer data.
1570 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001571 bool consumed;
1572 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1573 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001574 mCurrentRawState.rawPointerData.clear();
1575 }
1576
1577 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1578 // with cooked pointer data that has the same ids and indices as the raw data.
1579 // The following code can use either the raw or cooked data, as needed.
1580 cookPointerData();
1581
1582 // Apply stylus pressure to current cooked state.
1583 applyExternalStylusTouchState(when);
1584
1585 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001586 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1587 mSource, mViewport.displayId, policyFlags,
1588 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001589
1590 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001591 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001592 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1593 uint32_t id = idBits.clearFirstMarkedBit();
1594 const RawPointerData::Pointer& pointer =
1595 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001596 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001597 mCurrentCookedState.stylusIdBits.markBit(id);
1598 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1599 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1600 mCurrentCookedState.fingerIdBits.markBit(id);
1601 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1602 mCurrentCookedState.mouseIdBits.markBit(id);
1603 }
1604 }
1605 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1606 uint32_t id = idBits.clearFirstMarkedBit();
1607 const RawPointerData::Pointer& pointer =
1608 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001609 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001610 mCurrentCookedState.stylusIdBits.markBit(id);
1611 }
1612 }
1613
1614 // Stylus takes precedence over all tools, then mouse, then finger.
1615 PointerUsage pointerUsage = mPointerUsage;
1616 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1617 mCurrentCookedState.mouseIdBits.clear();
1618 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001619 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001620 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1621 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001622 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001623 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1624 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001625 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001626 }
1627
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001628 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001629 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001630 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001631 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001632 out += dispatchButtonRelease(when, readTime, policyFlags);
1633 out += dispatchHoverExit(when, readTime, policyFlags);
1634 out += dispatchTouches(when, readTime, policyFlags);
1635 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1636 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001637 }
1638
1639 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1640 mCurrentMotionAborted = false;
1641 }
1642 }
1643
1644 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001645 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1646 mSource, mViewport.displayId, policyFlags,
1647 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001648
1649 // Clear some transient state.
1650 mCurrentRawState.rawVScroll = 0;
1651 mCurrentRawState.rawHScroll = 0;
1652
1653 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001654 mLastRawState = mCurrentRawState;
1655 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001656 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001657}
1658
Garfield Tanc734e4f2021-01-15 20:01:39 -08001659void TouchInputMapper::updateTouchSpots() {
1660 if (!mConfig.showTouches || mPointerController == nullptr) {
1661 return;
1662 }
1663
1664 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1665 // clear touch spots.
1666 if (mDeviceMode != DeviceMode::DIRECT &&
1667 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1668 return;
1669 }
1670
1671 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1672 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1673
1674 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001675 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1676 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001677 mCurrentCookedState.cookedPointerData.touchingIdBits,
1678 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001679}
1680
1681bool TouchInputMapper::isTouchScreen() {
1682 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1683 mParameters.hasAssociatedDisplay;
1684}
1685
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001686void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001687 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1688 // If any of the external buttons are already pressed by the touch device, ignore them.
1689 const int32_t pressedButtons = ~mCurrentRawState.buttonState & mExternalStylusState.buttons;
1690 const int32_t releasedButtons =
1691 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1692
1693 mCurrentRawState.buttonState |= pressedButtons;
1694 mCurrentRawState.buttonState &= ~releasedButtons;
1695
1696 mExternalStylusButtonsApplied |= pressedButtons;
1697 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001698 }
1699}
1700
1701void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1702 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1703 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001704 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1705 return;
1706 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001707
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001708 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1709 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1710 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1711 : 0.f;
1712 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1713 pressure = *mExternalStylusState.pressure;
1714 }
1715 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1716 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001717
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001718 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001719 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001720 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001721 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001722 }
1723}
1724
1725bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001726 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001727 return false;
1728 }
1729
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001730 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001731 if (mFusedStylusPointerId &&
1732 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001733 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001734 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001735 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001736 }
1737
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001738 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1739 state.rawPointerData.pointerCount != 0;
1740 if (!initialDown) {
1741 return false;
1742 }
1743
1744 if (!mExternalStylusState.pressure) {
1745 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1746 return false;
1747 }
1748
1749 if (*mExternalStylusState.pressure != 0.0f) {
1750 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1751 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1752 return false;
1753 }
1754
1755 if (timeout) {
1756 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1757 mFusedStylusPointerId.reset();
1758 mExternalStylusFusionTimeout = LLONG_MAX;
1759 return false;
1760 }
1761
1762 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1763 // being processed until we either get pressure data or timeout.
1764 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1765 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1766 }
1767 ALOGD_IF(DEBUG_STYLUS_FUSION,
1768 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1769 mExternalStylusFusionTimeout);
1770 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1771 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001772}
1773
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001774std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1775 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001776 if (mDeviceMode == DeviceMode::POINTER) {
1777 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001778 // Since this is a synthetic event, we can consider its latency to be zero
1779 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001780 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001781 }
Michael Wright227c5542020-07-02 18:30:52 +01001782 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001783 if (mExternalStylusFusionTimeout <= when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001784 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001785 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1786 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1787 }
1788 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001789 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001790}
1791
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001792std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1793 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001794 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001795 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001796 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001797 // The following three cases are handled here:
1798 // - We're in the middle of a fused stream of data;
1799 // - We're waiting on external stylus data before dispatching the initial down; or
1800 // - Only the button state, which is not reported through a specific pointer, has changed.
1801 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001802 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001803 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001804 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001805 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001806}
1807
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001808std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1809 uint32_t policyFlags, bool& outConsumed) {
1810 outConsumed = false;
1811 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001812 // Check for release of a virtual key.
1813 if (mCurrentVirtualKey.down) {
1814 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1815 // Pointer went up while virtual key was down.
1816 mCurrentVirtualKey.down = false;
1817 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001818 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1819 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1820 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001821 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1822 AKEY_EVENT_FLAG_FROM_SYSTEM |
1823 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001824 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001825 outConsumed = true;
1826 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001827 }
1828
1829 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1830 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1831 const RawPointerData::Pointer& pointer =
1832 mCurrentRawState.rawPointerData.pointerForId(id);
1833 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1834 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1835 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001836 outConsumed = true;
1837 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001838 }
1839 }
1840
1841 // Pointer left virtual key area or another pointer also went down.
1842 // Send key cancellation but do not consume the touch yet.
1843 // This is useful when the user swipes through from the virtual key area
1844 // into the main display surface.
1845 mCurrentVirtualKey.down = false;
1846 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001847 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1848 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001849 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1850 AKEY_EVENT_FLAG_FROM_SYSTEM |
1851 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1852 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001853 }
1854 }
1855
1856 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1857 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1858 // Pointer just went down. Check for virtual key press or off-screen touches.
1859 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1860 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001861 // Skip checking whether the pointer is inside the physical frame if the device is in
1862 // unscaled mode.
1863 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1864 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001865 // If exactly one pointer went down, check for virtual key hit.
1866 // Otherwise we will drop the entire stroke.
1867 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1868 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1869 if (virtualKey) {
1870 mCurrentVirtualKey.down = true;
1871 mCurrentVirtualKey.downTime = when;
1872 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1873 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1874 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001875 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1876 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001877
1878 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001879 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1880 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1881 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001882 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1883 AKEY_EVENT_ACTION_DOWN,
1884 AKEY_EVENT_FLAG_FROM_SYSTEM |
1885 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001886 }
1887 }
1888 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001889 outConsumed = true;
1890 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001891 }
1892 }
1893
1894 // Disable all virtual key touches that happen within a short time interval of the
1895 // most recent touch within the screen area. The idea is to filter out stray
1896 // virtual key presses when interacting with the touch screen.
1897 //
1898 // Problems we're trying to solve:
1899 //
1900 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1901 // virtual key area that is implemented by a separate touch panel and accidentally
1902 // triggers a virtual key.
1903 //
1904 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1905 // area and accidentally triggers a virtual key. This often happens when virtual keys
1906 // are layed out below the screen near to where the on screen keyboard's space bar
1907 // is displayed.
1908 if (mConfig.virtualKeyQuietTime > 0 &&
1909 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001910 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001911 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001912 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001913}
1914
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001915NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1916 uint32_t policyFlags, int32_t keyEventAction,
1917 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001918 int32_t keyCode = mCurrentVirtualKey.keyCode;
1919 int32_t scanCode = mCurrentVirtualKey.scanCode;
1920 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001921 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001922 policyFlags |= POLICY_FLAG_VIRTUAL;
1923
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001924 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1925 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1926 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001927}
1928
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001929std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1930 uint32_t policyFlags) {
1931 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001932 if (mCurrentMotionAborted) {
1933 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001934 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001935 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001936 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1937 if (!currentIdBits.isEmpty()) {
1938 int32_t metaState = getContext()->getGlobalMetaState();
1939 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001940 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001941 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1942 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001943 mCurrentCookedState.cookedPointerData.pointerProperties,
1944 mCurrentCookedState.cookedPointerData.pointerCoords,
1945 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1946 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1947 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001948 mCurrentMotionAborted = true;
1949 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001950 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001951}
1952
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001953// Updates pointer coords and properties for pointers with specified ids that have moved.
1954// Returns true if any of them changed.
1955static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1956 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1957 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1958 BitSet32 idBits) {
1959 bool changed = false;
1960 while (!idBits.isEmpty()) {
1961 uint32_t id = idBits.clearFirstMarkedBit();
1962 uint32_t inIndex = inIdToIndex[id];
1963 uint32_t outIndex = outIdToIndex[id];
1964
1965 const PointerProperties& curInProperties = inProperties[inIndex];
1966 const PointerCoords& curInCoords = inCoords[inIndex];
1967 PointerProperties& curOutProperties = outProperties[outIndex];
1968 PointerCoords& curOutCoords = outCoords[outIndex];
1969
1970 if (curInProperties != curOutProperties) {
1971 curOutProperties.copyFrom(curInProperties);
1972 changed = true;
1973 }
1974
1975 if (curInCoords != curOutCoords) {
1976 curOutCoords.copyFrom(curInCoords);
1977 changed = true;
1978 }
1979 }
1980 return changed;
1981}
1982
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001983std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1984 uint32_t policyFlags) {
1985 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001986 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1987 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1988 int32_t metaState = getContext()->getGlobalMetaState();
1989 int32_t buttonState = mCurrentCookedState.buttonState;
1990
1991 if (currentIdBits == lastIdBits) {
1992 if (!currentIdBits.isEmpty()) {
1993 // No pointer id changes so this is a move event.
1994 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001995 out.push_back(
1996 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1997 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1998 mCurrentCookedState.cookedPointerData.pointerProperties,
1999 mCurrentCookedState.cookedPointerData.pointerCoords,
2000 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2001 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2002 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002003 }
2004 } else {
2005 // There may be pointers going up and pointers going down and pointers moving
2006 // all at the same time.
2007 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2008 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2009 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2010 BitSet32 dispatchedIdBits(lastIdBits.value);
2011
2012 // Update last coordinates of pointers that have moved so that we observe the new
2013 // pointer positions at the same time as other pointers that have just gone up.
2014 bool moveNeeded =
2015 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2016 mCurrentCookedState.cookedPointerData.pointerCoords,
2017 mCurrentCookedState.cookedPointerData.idToIndex,
2018 mLastCookedState.cookedPointerData.pointerProperties,
2019 mLastCookedState.cookedPointerData.pointerCoords,
2020 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2021 if (buttonState != mLastCookedState.buttonState) {
2022 moveNeeded = true;
2023 }
2024
2025 // Dispatch pointer up events.
2026 while (!upIdBits.isEmpty()) {
2027 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002028 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002029 if (isCanceled) {
2030 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2031 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002032 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2033 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2034 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2035 buttonState, 0,
2036 mLastCookedState.cookedPointerData.pointerProperties,
2037 mLastCookedState.cookedPointerData.pointerCoords,
2038 mLastCookedState.cookedPointerData.idToIndex,
2039 dispatchedIdBits, upId, mOrientedXPrecision,
2040 mOrientedYPrecision, mDownTime,
2041 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002042 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002043 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002044 }
2045
2046 // Dispatch move events if any of the remaining pointers moved from their old locations.
2047 // Although applications receive new locations as part of individual pointer up
2048 // events, they do not generally handle them except when presented in a move event.
2049 if (moveNeeded && !moveIdBits.isEmpty()) {
2050 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002051 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2052 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2053 mCurrentCookedState.cookedPointerData.pointerProperties,
2054 mCurrentCookedState.cookedPointerData.pointerCoords,
2055 mCurrentCookedState.cookedPointerData.idToIndex,
2056 dispatchedIdBits, -1, mOrientedXPrecision,
2057 mOrientedYPrecision, mDownTime,
2058 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002059 }
2060
2061 // Dispatch pointer down events using the new pointer locations.
2062 while (!downIdBits.isEmpty()) {
2063 uint32_t downId = downIdBits.clearFirstMarkedBit();
2064 dispatchedIdBits.markBit(downId);
2065
2066 if (dispatchedIdBits.count() == 1) {
2067 // First pointer is going down. Set down time.
2068 mDownTime = when;
2069 }
2070
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002071 out.push_back(
2072 dispatchMotion(when, readTime, policyFlags, mSource,
2073 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2074 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2075 mCurrentCookedState.cookedPointerData.pointerCoords,
2076 mCurrentCookedState.cookedPointerData.idToIndex,
2077 dispatchedIdBits, downId, mOrientedXPrecision,
2078 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002079 }
2080 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002081 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002082}
2083
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002084std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2085 uint32_t policyFlags) {
2086 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002087 if (mSentHoverEnter &&
2088 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2089 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2090 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002091 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2092 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2093 mLastCookedState.buttonState, 0,
2094 mLastCookedState.cookedPointerData.pointerProperties,
2095 mLastCookedState.cookedPointerData.pointerCoords,
2096 mLastCookedState.cookedPointerData.idToIndex,
2097 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2098 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2099 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002100 mSentHoverEnter = false;
2101 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002102 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002103}
2104
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002105std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2106 uint32_t policyFlags) {
2107 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002108 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2109 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2110 int32_t metaState = getContext()->getGlobalMetaState();
2111 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002112 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2113 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2114 mCurrentRawState.buttonState, 0,
2115 mCurrentCookedState.cookedPointerData.pointerProperties,
2116 mCurrentCookedState.cookedPointerData.pointerCoords,
2117 mCurrentCookedState.cookedPointerData.idToIndex,
2118 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2119 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2120 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002121 mSentHoverEnter = true;
2122 }
2123
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002124 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2125 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2126 mCurrentRawState.buttonState, 0,
2127 mCurrentCookedState.cookedPointerData.pointerProperties,
2128 mCurrentCookedState.cookedPointerData.pointerCoords,
2129 mCurrentCookedState.cookedPointerData.idToIndex,
2130 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2131 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2132 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002133 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002134 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002135}
2136
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002137std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2138 uint32_t policyFlags) {
2139 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002140 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2141 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2142 const int32_t metaState = getContext()->getGlobalMetaState();
2143 int32_t buttonState = mLastCookedState.buttonState;
2144 while (!releasedButtons.isEmpty()) {
2145 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2146 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002147 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2148 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2149 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002150 mLastCookedState.cookedPointerData.pointerProperties,
2151 mLastCookedState.cookedPointerData.pointerCoords,
2152 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002153 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2154 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002155 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002156 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002157}
2158
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002159std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2160 uint32_t policyFlags) {
2161 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002162 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2163 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2164 const int32_t metaState = getContext()->getGlobalMetaState();
2165 int32_t buttonState = mLastCookedState.buttonState;
2166 while (!pressedButtons.isEmpty()) {
2167 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2168 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002169 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2170 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2171 buttonState, 0,
2172 mCurrentCookedState.cookedPointerData.pointerProperties,
2173 mCurrentCookedState.cookedPointerData.pointerCoords,
2174 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2175 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2176 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002177 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002178 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002179}
2180
2181const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2182 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2183 return cookedPointerData.touchingIdBits;
2184 }
2185 return cookedPointerData.hoveringIdBits;
2186}
2187
2188void TouchInputMapper::cookPointerData() {
2189 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2190
2191 mCurrentCookedState.cookedPointerData.clear();
2192 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2193 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2194 mCurrentRawState.rawPointerData.hoveringIdBits;
2195 mCurrentCookedState.cookedPointerData.touchingIdBits =
2196 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002197 mCurrentCookedState.cookedPointerData.canceledIdBits =
2198 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002199
2200 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2201 mCurrentCookedState.buttonState = 0;
2202 } else {
2203 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2204 }
2205
2206 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002207 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002208 for (uint32_t i = 0; i < currentPointerCount; i++) {
2209 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2210
2211 // Size
2212 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2213 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002214 case Calibration::SizeCalibration::GEOMETRIC:
2215 case Calibration::SizeCalibration::DIAMETER:
2216 case Calibration::SizeCalibration::BOX:
2217 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002218 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2219 touchMajor = in.touchMajor;
2220 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2221 toolMajor = in.toolMajor;
2222 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2223 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2224 : in.touchMajor;
2225 } else if (mRawPointerAxes.touchMajor.valid) {
2226 toolMajor = touchMajor = in.touchMajor;
2227 toolMinor = touchMinor =
2228 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2229 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2230 : in.touchMajor;
2231 } else if (mRawPointerAxes.toolMajor.valid) {
2232 touchMajor = toolMajor = in.toolMajor;
2233 touchMinor = toolMinor =
2234 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2235 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2236 : in.toolMajor;
2237 } else {
2238 ALOG_ASSERT(false,
2239 "No touch or tool axes. "
2240 "Size calibration should have been resolved to NONE.");
2241 touchMajor = 0;
2242 touchMinor = 0;
2243 toolMajor = 0;
2244 toolMinor = 0;
2245 size = 0;
2246 }
2247
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002248 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002249 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2250 if (touchingCount > 1) {
2251 touchMajor /= touchingCount;
2252 touchMinor /= touchingCount;
2253 toolMajor /= touchingCount;
2254 toolMinor /= touchingCount;
2255 size /= touchingCount;
2256 }
2257 }
2258
Michael Wright227c5542020-07-02 18:30:52 +01002259 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002260 touchMajor *= mGeometricScale;
2261 touchMinor *= mGeometricScale;
2262 toolMajor *= mGeometricScale;
2263 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002264 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002265 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2266 touchMinor = touchMajor;
2267 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2268 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002269 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002270 touchMinor = touchMajor;
2271 toolMinor = toolMajor;
2272 }
2273
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002274 mCalibration.applySizeScaleAndBias(touchMajor);
2275 mCalibration.applySizeScaleAndBias(touchMinor);
2276 mCalibration.applySizeScaleAndBias(toolMajor);
2277 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002278 size *= mSizeScale;
2279 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002280 case Calibration::SizeCalibration::DEFAULT:
2281 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2282 break;
2283 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002284 touchMajor = 0;
2285 touchMinor = 0;
2286 toolMajor = 0;
2287 toolMinor = 0;
2288 size = 0;
2289 break;
2290 }
2291
2292 // Pressure
2293 float pressure;
2294 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002295 case Calibration::PressureCalibration::PHYSICAL:
2296 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002297 pressure = in.pressure * mPressureScale;
2298 break;
2299 default:
2300 pressure = in.isHovering ? 0 : 1;
2301 break;
2302 }
2303
2304 // Tilt and Orientation
2305 float tilt;
2306 float orientation;
2307 if (mHaveTilt) {
2308 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2309 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2310 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2311 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2312 } else {
2313 tilt = 0;
2314
2315 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002316 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002317 orientation = in.orientation * mOrientationScale;
2318 break;
Michael Wright227c5542020-07-02 18:30:52 +01002319 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002320 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2321 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2322 if (c1 != 0 || c2 != 0) {
2323 orientation = atan2f(c1, c2) * 0.5f;
2324 float confidence = hypotf(c1, c2);
2325 float scale = 1.0f + confidence / 16.0f;
2326 touchMajor *= scale;
2327 touchMinor /= scale;
2328 toolMajor *= scale;
2329 toolMinor /= scale;
2330 } else {
2331 orientation = 0;
2332 }
2333 break;
2334 }
2335 default:
2336 orientation = 0;
2337 }
2338 }
2339
2340 // Distance
2341 float distance;
2342 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002343 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002344 distance = in.distance * mDistanceScale;
2345 break;
2346 default:
2347 distance = 0;
2348 }
2349
2350 // Coverage
2351 int32_t rawLeft, rawTop, rawRight, rawBottom;
2352 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002353 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002354 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2355 rawRight = in.toolMinor & 0x0000ffff;
2356 rawBottom = in.toolMajor & 0x0000ffff;
2357 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2358 break;
2359 default:
2360 rawLeft = rawTop = rawRight = rawBottom = 0;
2361 break;
2362 }
2363
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002364 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2365 vec2 transformed = {in.x, in.y};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002366 // TODO: Adjust coverage coords?
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002367 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2368 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002369
Prabir Pradhan1728b212021-10-19 16:00:03 -07002370 // Adjust X, Y, and coverage coords for input device orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002371 float left, top, right, bottom;
2372
Prabir Pradhan1728b212021-10-19 16:00:03 -07002373 switch (mInputDeviceOrientation) {
Michael Wrighta9cf4192022-12-01 23:46:39 +00002374 case ui::ROTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002375 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
2376 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2377 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2378 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002379 orientation -= M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002380 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002381 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002382 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002383 }
2384 break;
Michael Wrighta9cf4192022-12-01 23:46:39 +00002385 case ui::ROTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002386 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2387 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002388 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2389 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002390 orientation -= M_PI;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002391 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002392 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002393 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002394 }
2395 break;
Michael Wrighta9cf4192022-12-01 23:46:39 +00002396 case ui::ROTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002397 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2398 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002399 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2400 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002401 orientation += M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002402 if (mOrientedRanges.orientation && orientation > mOrientedRanges.orientation->max) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002403 orientation -=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002404 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002405 }
2406 break;
2407 default:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002408 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
2409 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2410 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2411 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002412 break;
2413 }
2414
2415 // Write output coords.
2416 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2417 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002418 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2419 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002420 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2421 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2422 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2423 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2424 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2425 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2426 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002427 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002428 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2429 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2430 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2431 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2432 } else {
2433 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2434 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2435 }
2436
Chris Ye364fdb52020-08-05 15:07:56 -07002437 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002438 uint32_t id = in.id;
2439 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2440 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2441 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002442 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2443 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002444 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2445 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2446 }
2447
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002448 // Write output properties.
2449 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002450 properties.clear();
2451 properties.id = id;
2452 properties.toolType = in.toolType;
2453
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002454 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002455 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002456 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002457 }
2458}
2459
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002460std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2461 uint32_t policyFlags,
2462 PointerUsage pointerUsage) {
2463 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002464 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002465 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002466 mPointerUsage = pointerUsage;
2467 }
2468
2469 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002470 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002471 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002472 break;
Michael Wright227c5542020-07-02 18:30:52 +01002473 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002474 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002475 break;
Michael Wright227c5542020-07-02 18:30:52 +01002476 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002477 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002478 break;
Michael Wright227c5542020-07-02 18:30:52 +01002479 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002480 break;
2481 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002482 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002483}
2484
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002485std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2486 uint32_t policyFlags) {
2487 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002488 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002489 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002490 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002491 break;
Michael Wright227c5542020-07-02 18:30:52 +01002492 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002493 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002494 break;
Michael Wright227c5542020-07-02 18:30:52 +01002495 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002496 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002497 break;
Michael Wright227c5542020-07-02 18:30:52 +01002498 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002499 break;
2500 }
2501
Michael Wright227c5542020-07-02 18:30:52 +01002502 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002503 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002504}
2505
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002506std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2507 uint32_t policyFlags,
2508 bool isTimeout) {
2509 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002510 // Update current gesture coordinates.
2511 bool cancelPreviousGesture, finishPreviousGesture;
2512 bool sendEvents =
2513 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2514 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002515 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002516 }
2517 if (finishPreviousGesture) {
2518 cancelPreviousGesture = false;
2519 }
2520
2521 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002522 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002523 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002524 if (finishPreviousGesture || cancelPreviousGesture) {
2525 mPointerController->clearSpots();
2526 }
2527
Michael Wright227c5542020-07-02 18:30:52 +01002528 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002529 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2530 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002531 mPointerGesture.currentGestureIdBits,
2532 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002533 }
2534 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002535 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002536 }
2537
2538 // Show or hide the pointer if needed.
2539 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002540 case PointerGesture::Mode::NEUTRAL:
2541 case PointerGesture::Mode::QUIET:
2542 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2543 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002544 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002545 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002546 }
2547 break;
Michael Wright227c5542020-07-02 18:30:52 +01002548 case PointerGesture::Mode::TAP:
2549 case PointerGesture::Mode::TAP_DRAG:
2550 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2551 case PointerGesture::Mode::HOVER:
2552 case PointerGesture::Mode::PRESS:
2553 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002554 // Unfade the pointer when the current gesture manipulates the
2555 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002556 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002557 break;
Michael Wright227c5542020-07-02 18:30:52 +01002558 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002559 // Fade the pointer when the current gesture manipulates a different
2560 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002561 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002562 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002563 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002564 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002565 }
2566 break;
2567 }
2568
2569 // Send events!
2570 int32_t metaState = getContext()->getGlobalMetaState();
2571 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002572 const MotionClassification classification =
2573 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2574 ? MotionClassification::TWO_FINGER_SWIPE
2575 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002576
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002577 uint32_t flags = 0;
2578
2579 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2580 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2581 }
2582
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002583 // Update last coordinates of pointers that have moved so that we observe the new
2584 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002585 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2586 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2587 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2588 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2589 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2590 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002591 bool moveNeeded = false;
2592 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2593 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2594 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2595 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2596 mPointerGesture.lastGestureIdBits.value);
2597 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2598 mPointerGesture.currentGestureCoords,
2599 mPointerGesture.currentGestureIdToIndex,
2600 mPointerGesture.lastGestureProperties,
2601 mPointerGesture.lastGestureCoords,
2602 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2603 if (buttonState != mLastCookedState.buttonState) {
2604 moveNeeded = true;
2605 }
2606 }
2607
2608 // Send motion events for all pointers that went up or were canceled.
2609 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2610 if (!dispatchedGestureIdBits.isEmpty()) {
2611 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002612 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002613 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002614 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002615 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2616 mPointerGesture.lastGestureProperties,
2617 mPointerGesture.lastGestureCoords,
2618 mPointerGesture.lastGestureIdToIndex,
2619 dispatchedGestureIdBits, -1, 0, 0,
2620 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002621
2622 dispatchedGestureIdBits.clear();
2623 } else {
2624 BitSet32 upGestureIdBits;
2625 if (finishPreviousGesture) {
2626 upGestureIdBits = dispatchedGestureIdBits;
2627 } else {
2628 upGestureIdBits.value =
2629 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2630 }
2631 while (!upGestureIdBits.isEmpty()) {
2632 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2633
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002634 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2635 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2636 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2637 mPointerGesture.lastGestureProperties,
2638 mPointerGesture.lastGestureCoords,
2639 mPointerGesture.lastGestureIdToIndex,
2640 dispatchedGestureIdBits, id, 0, 0,
2641 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002642
2643 dispatchedGestureIdBits.clearBit(id);
2644 }
2645 }
2646 }
2647
2648 // Send motion events for all pointers that moved.
2649 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002650 out.push_back(
2651 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2652 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2653 mPointerGesture.currentGestureProperties,
2654 mPointerGesture.currentGestureCoords,
2655 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2656 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002657 }
2658
2659 // Send motion events for all pointers that went down.
2660 if (down) {
2661 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2662 ~dispatchedGestureIdBits.value);
2663 while (!downGestureIdBits.isEmpty()) {
2664 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2665 dispatchedGestureIdBits.markBit(id);
2666
2667 if (dispatchedGestureIdBits.count() == 1) {
2668 mPointerGesture.downTime = when;
2669 }
2670
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002671 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2672 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2673 buttonState, 0, mPointerGesture.currentGestureProperties,
2674 mPointerGesture.currentGestureCoords,
2675 mPointerGesture.currentGestureIdToIndex,
2676 dispatchedGestureIdBits, id, 0, 0,
2677 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002678 }
2679 }
2680
2681 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002682 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002683 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2684 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2685 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2686 mPointerGesture.currentGestureProperties,
2687 mPointerGesture.currentGestureCoords,
2688 mPointerGesture.currentGestureIdToIndex,
2689 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2690 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002691 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2692 // Synthesize a hover move event after all pointers go up to indicate that
2693 // the pointer is hovering again even if the user is not currently touching
2694 // the touch pad. This ensures that a view will receive a fresh hover enter
2695 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002696 float x, y;
2697 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002698
2699 PointerProperties pointerProperties;
2700 pointerProperties.clear();
2701 pointerProperties.id = 0;
2702 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2703
2704 PointerCoords pointerCoords;
2705 pointerCoords.clear();
2706 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2707 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2708
2709 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002710 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2711 mSource, displayId, policyFlags,
2712 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2713 buttonState, MotionClassification::NONE,
2714 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2715 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2716 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002717 }
2718
2719 // Update state.
2720 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2721 if (!down) {
2722 mPointerGesture.lastGestureIdBits.clear();
2723 } else {
2724 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2725 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2726 uint32_t id = idBits.clearFirstMarkedBit();
2727 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2728 mPointerGesture.lastGestureProperties[index].copyFrom(
2729 mPointerGesture.currentGestureProperties[index]);
2730 mPointerGesture.lastGestureCoords[index].copyFrom(
2731 mPointerGesture.currentGestureCoords[index]);
2732 mPointerGesture.lastGestureIdToIndex[id] = index;
2733 }
2734 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002735 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002736}
2737
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002738std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2739 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002740 const MotionClassification classification =
2741 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2742 ? MotionClassification::TWO_FINGER_SWIPE
2743 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002744 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002745 // Cancel previously dispatches pointers.
2746 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2747 int32_t metaState = getContext()->getGlobalMetaState();
2748 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002749 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002750 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2751 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002752 mPointerGesture.lastGestureProperties,
2753 mPointerGesture.lastGestureCoords,
2754 mPointerGesture.lastGestureIdToIndex,
2755 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2756 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002757 }
2758
2759 // Reset the current pointer gesture.
2760 mPointerGesture.reset();
2761 mPointerVelocityControl.reset();
2762
2763 // Remove any current spots.
2764 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002765 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002766 mPointerController->clearSpots();
2767 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002768 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002769}
2770
2771bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2772 bool* outFinishPreviousGesture, bool isTimeout) {
2773 *outCancelPreviousGesture = false;
2774 *outFinishPreviousGesture = false;
2775
2776 // Handle TAP timeout.
2777 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002778 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002779
Michael Wright227c5542020-07-02 18:30:52 +01002780 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002781 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2782 // The tap/drag timeout has not yet expired.
2783 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2784 mConfig.pointerGestureTapDragInterval);
2785 } else {
2786 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002787 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002788 *outFinishPreviousGesture = true;
2789
2790 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002791 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002792 mPointerGesture.currentGestureIdBits.clear();
2793
2794 mPointerVelocityControl.reset();
2795 return true;
2796 }
2797 }
2798
2799 // We did not handle this timeout.
2800 return false;
2801 }
2802
2803 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2804 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2805
2806 // Update the velocity tracker.
2807 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002808 std::vector<float> positionsX;
2809 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002810 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002811 uint32_t id = idBits.clearFirstMarkedBit();
2812 const RawPointerData::Pointer& pointer =
2813 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002814 positionsX.push_back(pointer.x * mPointerXMovementScale);
2815 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002816 }
2817 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002818 {{AMOTION_EVENT_AXIS_X, positionsX},
2819 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002820 }
2821
2822 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2823 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002824 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2825 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2826 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002827 mPointerGesture.resetTap();
2828 }
2829
2830 // Pick a new active touch id if needed.
2831 // Choose an arbitrary pointer that just went down, if there is one.
2832 // Otherwise choose an arbitrary remaining pointer.
2833 // This guarantees we always have an active touch id when there is at least one pointer.
2834 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002835 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002836 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002837 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002838 mPointerGesture.firstTouchTime = when;
2839 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002840 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2841 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2842 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2843 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002844 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002845 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002846
2847 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002848 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002849 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002850 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2851 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2852 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002853 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002854 *outFinishPreviousGesture = true;
2855 }
2856
2857 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002858 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002859 mPointerGesture.currentGestureIdBits.clear();
2860
2861 mPointerVelocityControl.reset();
2862 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2863 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2864 // The pointer follows the active touch point.
2865 // Emit DOWN, MOVE, UP events at the pointer location.
2866 //
2867 // Only the active touch matters; other fingers are ignored. This policy helps
2868 // to handle the case where the user places a second finger on the touch pad
2869 // to apply the necessary force to depress an integrated button below the surface.
2870 // We don't want the second finger to be delivered to applications.
2871 //
2872 // For this to work well, we need to make sure to track the pointer that is really
2873 // active. If the user first puts one finger down to click then adds another
2874 // finger to drag then the active pointer should switch to the finger that is
2875 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002876 ALOGD_IF(DEBUG_GESTURES,
2877 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2878 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002879 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002880 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002881 *outFinishPreviousGesture = true;
2882 mPointerGesture.activeGestureId = 0;
2883 }
2884
2885 // Switch pointers if needed.
2886 // Find the fastest pointer and follow it.
2887 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002888 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002889 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002890 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002891 ALOGD_IF(DEBUG_GESTURES,
2892 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2893 "bestSpeed=%0.3f",
2894 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002895 }
2896 }
2897
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002898 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002899 // When using spots, the click will occur at the position of the anchor
2900 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002901 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002902 } else {
2903 mPointerVelocityControl.reset();
2904 }
2905
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002906 float x, y;
2907 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002908
Michael Wright227c5542020-07-02 18:30:52 +01002909 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002910 mPointerGesture.currentGestureIdBits.clear();
2911 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2912 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2913 mPointerGesture.currentGestureProperties[0].clear();
2914 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2915 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2916 mPointerGesture.currentGestureCoords[0].clear();
2917 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2918 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2919 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2920 } else if (currentFingerCount == 0) {
2921 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002922 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002923 *outFinishPreviousGesture = true;
2924 }
2925
2926 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2927 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2928 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002929 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2930 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002931 lastFingerCount == 1) {
2932 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002933 float x, y;
2934 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002935 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2936 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002937 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002938
2939 mPointerGesture.tapUpTime = when;
2940 getContext()->requestTimeoutAtTime(when +
2941 mConfig.pointerGestureTapDragInterval);
2942
2943 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002944 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002945 mPointerGesture.currentGestureIdBits.clear();
2946 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2947 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2948 mPointerGesture.currentGestureProperties[0].clear();
2949 mPointerGesture.currentGestureProperties[0].id =
2950 mPointerGesture.activeGestureId;
2951 mPointerGesture.currentGestureProperties[0].toolType =
2952 AMOTION_EVENT_TOOL_TYPE_FINGER;
2953 mPointerGesture.currentGestureCoords[0].clear();
2954 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2955 mPointerGesture.tapX);
2956 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2957 mPointerGesture.tapY);
2958 mPointerGesture.currentGestureCoords[0]
2959 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2960
2961 tapped = true;
2962 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002963 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2964 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002965 }
2966 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002967 if (DEBUG_GESTURES) {
2968 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2969 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2970 (when - mPointerGesture.tapDownTime) * 0.000001f);
2971 } else {
2972 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2973 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002974 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002975 }
2976 }
2977
2978 mPointerVelocityControl.reset();
2979
2980 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002981 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002982 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002983 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002984 mPointerGesture.currentGestureIdBits.clear();
2985 }
2986 } else if (currentFingerCount == 1) {
2987 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2988 // The pointer follows the active touch point.
2989 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2990 // When in TAP_DRAG, emit MOVE events at the pointer location.
2991 ALOG_ASSERT(activeTouchId >= 0);
2992
Michael Wright227c5542020-07-02 18:30:52 +01002993 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2994 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002995 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002996 float x, y;
2997 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002998 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2999 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01003000 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003001 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003002 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
3003 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003004 }
3005 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003006 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3007 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003008 }
Michael Wright227c5542020-07-02 18:30:52 +01003009 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3010 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003011 }
3012
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003013 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003014 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003015 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003016 } else {
3017 mPointerVelocityControl.reset();
3018 }
3019
3020 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003021 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003022 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003023 down = true;
3024 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003025 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003026 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003027 *outFinishPreviousGesture = true;
3028 }
3029 mPointerGesture.activeGestureId = 0;
3030 down = false;
3031 }
3032
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003033 float x, y;
3034 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003035
3036 mPointerGesture.currentGestureIdBits.clear();
3037 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3038 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3039 mPointerGesture.currentGestureProperties[0].clear();
3040 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3041 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3042 mPointerGesture.currentGestureCoords[0].clear();
3043 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3044 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3045 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3046 down ? 1.0f : 0.0f);
3047
3048 if (lastFingerCount == 0 && currentFingerCount != 0) {
3049 mPointerGesture.resetTap();
3050 mPointerGesture.tapDownTime = when;
3051 mPointerGesture.tapX = x;
3052 mPointerGesture.tapY = y;
3053 }
3054 } else {
3055 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003056 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003057 }
3058
3059 mPointerController->setButtonState(mCurrentRawState.buttonState);
3060
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003061 if (DEBUG_GESTURES) {
3062 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3063 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3064 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3065 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3066 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3067 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3068 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3069 uint32_t id = idBits.clearFirstMarkedBit();
3070 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3071 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3072 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3073 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3074 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3075 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3076 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3077 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3078 }
3079 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3080 uint32_t id = idBits.clearFirstMarkedBit();
3081 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3082 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3083 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3084 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3085 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3086 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3087 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3088 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3089 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003090 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003091 return true;
3092}
3093
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003094bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3095 if (mPointerGesture.activeTouchId < 0) {
3096 mPointerGesture.resetQuietTime();
3097 return false;
3098 }
3099
3100 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3101 return true;
3102 }
3103
3104 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3105 bool isQuietTime = false;
3106 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3107 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3108 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3109 currentFingerCount < 2) {
3110 // Enter quiet time when exiting swipe or freeform state.
3111 // This is to prevent accidentally entering the hover state and flinging the
3112 // pointer when finishing a swipe and there is still one pointer left onscreen.
3113 isQuietTime = true;
3114 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3115 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3116 // Enter quiet time when releasing the button and there are still two or more
3117 // fingers down. This may indicate that one finger was used to press the button
3118 // but it has not gone up yet.
3119 isQuietTime = true;
3120 }
3121 if (isQuietTime) {
3122 mPointerGesture.quietTime = when;
3123 }
3124 return isQuietTime;
3125}
3126
3127std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3128 int32_t bestId = -1;
3129 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3130 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3131 uint32_t id = idBits.clearFirstMarkedBit();
3132 std::optional<float> vx =
3133 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3134 std::optional<float> vy =
3135 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3136 if (vx && vy) {
3137 float speed = hypotf(*vx, *vy);
3138 if (speed > bestSpeed) {
3139 bestId = id;
3140 bestSpeed = speed;
3141 }
3142 }
3143 }
3144 return std::make_pair(bestId, bestSpeed);
3145}
3146
3147void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3148 bool* finishPreviousGesture) {
3149 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3150 // to move before deciding what to do.
3151 //
3152 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3153 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3154 // just a press or long-press at the pointer location.
3155 //
3156 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3157 // pointer location.
3158 //
3159 // When the two fingers move enough or when additional fingers are added, we make a decision to
3160 // transition into SWIPE or FREEFORM mode accordingly.
3161 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3162 ALOG_ASSERT(activeTouchId >= 0);
3163
3164 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3165 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3166 bool settled =
3167 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3168 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3169 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3170 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3171 *finishPreviousGesture = true;
3172 } else if (!settled && currentFingerCount > lastFingerCount) {
3173 // Additional pointers have gone down but not yet settled.
3174 // Reset the gesture.
3175 ALOGD_IF(DEBUG_GESTURES,
3176 "Gestures: Resetting gesture since additional pointers went down for "
3177 "MULTITOUCH, settle time remaining %0.3fms",
3178 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3179 when) * 0.000001f);
3180 *cancelPreviousGesture = true;
3181 } else {
3182 // Continue previous gesture.
3183 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3184 }
3185
3186 if (*finishPreviousGesture || *cancelPreviousGesture) {
3187 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3188 mPointerGesture.activeGestureId = 0;
3189 mPointerGesture.referenceIdBits.clear();
3190 mPointerVelocityControl.reset();
3191
3192 // Use the centroid and pointer location as the reference points for the gesture.
3193 ALOGD_IF(DEBUG_GESTURES,
3194 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3195 "%0.3fms",
3196 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3197 when) * 0.000001f);
3198 mCurrentRawState.rawPointerData
3199 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3200 &mPointerGesture.referenceTouchY);
3201 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3202 &mPointerGesture.referenceGestureY);
3203 }
3204
3205 // Clear the reference deltas for fingers not yet included in the reference calculation.
3206 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3207 ~mPointerGesture.referenceIdBits.value);
3208 !idBits.isEmpty();) {
3209 uint32_t id = idBits.clearFirstMarkedBit();
3210 mPointerGesture.referenceDeltas[id].dx = 0;
3211 mPointerGesture.referenceDeltas[id].dy = 0;
3212 }
3213 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3214
3215 // Add delta for all fingers and calculate a common movement delta.
3216 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3217 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3218 mCurrentCookedState.fingerIdBits.value);
3219 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3220 bool first = (idBits == commonIdBits);
3221 uint32_t id = idBits.clearFirstMarkedBit();
3222 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3223 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3224 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3225 delta.dx += cpd.x - lpd.x;
3226 delta.dy += cpd.y - lpd.y;
3227
3228 if (first) {
3229 commonDeltaRawX = delta.dx;
3230 commonDeltaRawY = delta.dy;
3231 } else {
3232 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3233 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3234 }
3235 }
3236
3237 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3238 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3239 float dist[MAX_POINTER_ID + 1];
3240 int32_t distOverThreshold = 0;
3241 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3242 uint32_t id = idBits.clearFirstMarkedBit();
3243 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3244 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3245 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3246 distOverThreshold += 1;
3247 }
3248 }
3249
3250 // Only transition when at least two pointers have moved further than
3251 // the minimum distance threshold.
3252 if (distOverThreshold >= 2) {
3253 if (currentFingerCount > 2) {
3254 // There are more than two pointers, switch to FREEFORM.
3255 ALOGD_IF(DEBUG_GESTURES,
3256 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3257 currentFingerCount);
3258 *cancelPreviousGesture = true;
3259 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3260 } else {
3261 // There are exactly two pointers.
3262 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3263 uint32_t id1 = idBits.clearFirstMarkedBit();
3264 uint32_t id2 = idBits.firstMarkedBit();
3265 const RawPointerData::Pointer& p1 =
3266 mCurrentRawState.rawPointerData.pointerForId(id1);
3267 const RawPointerData::Pointer& p2 =
3268 mCurrentRawState.rawPointerData.pointerForId(id2);
3269 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3270 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3271 // There are two pointers but they are too far apart for a SWIPE,
3272 // switch to FREEFORM.
3273 ALOGD_IF(DEBUG_GESTURES,
3274 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3275 mutualDistance, mPointerGestureMaxSwipeWidth);
3276 *cancelPreviousGesture = true;
3277 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3278 } else {
3279 // There are two pointers. Wait for both pointers to start moving
3280 // before deciding whether this is a SWIPE or FREEFORM gesture.
3281 float dist1 = dist[id1];
3282 float dist2 = dist[id2];
3283 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3284 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3285 // Calculate the dot product of the displacement vectors.
3286 // When the vectors are oriented in approximately the same direction,
3287 // the angle betweeen them is near zero and the cosine of the angle
3288 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3289 // mag(v2).
3290 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3291 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3292 float dx1 = delta1.dx * mPointerXZoomScale;
3293 float dy1 = delta1.dy * mPointerYZoomScale;
3294 float dx2 = delta2.dx * mPointerXZoomScale;
3295 float dy2 = delta2.dy * mPointerYZoomScale;
3296 float dot = dx1 * dx2 + dy1 * dy2;
3297 float cosine = dot / (dist1 * dist2); // denominator always > 0
3298 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3299 // Pointers are moving in the same direction. Switch to SWIPE.
3300 ALOGD_IF(DEBUG_GESTURES,
3301 "Gestures: PRESS transitioned to SWIPE, "
3302 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3303 "cosine %0.3f >= %0.3f",
3304 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3305 mConfig.pointerGestureMultitouchMinDistance, cosine,
3306 mConfig.pointerGestureSwipeTransitionAngleCosine);
3307 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3308 } else {
3309 // Pointers are moving in different directions. Switch to FREEFORM.
3310 ALOGD_IF(DEBUG_GESTURES,
3311 "Gestures: PRESS transitioned to FREEFORM, "
3312 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3313 "cosine %0.3f < %0.3f",
3314 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3315 mConfig.pointerGestureMultitouchMinDistance, cosine,
3316 mConfig.pointerGestureSwipeTransitionAngleCosine);
3317 *cancelPreviousGesture = true;
3318 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3319 }
3320 }
3321 }
3322 }
3323 }
3324 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3325 // Switch from SWIPE to FREEFORM if additional pointers go down.
3326 // Cancel previous gesture.
3327 if (currentFingerCount > 2) {
3328 ALOGD_IF(DEBUG_GESTURES,
3329 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3330 currentFingerCount);
3331 *cancelPreviousGesture = true;
3332 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3333 }
3334 }
3335
3336 // Move the reference points based on the overall group motion of the fingers
3337 // except in PRESS mode while waiting for a transition to occur.
3338 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3339 (commonDeltaRawX || commonDeltaRawY)) {
3340 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3341 uint32_t id = idBits.clearFirstMarkedBit();
3342 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3343 delta.dx = 0;
3344 delta.dy = 0;
3345 }
3346
3347 mPointerGesture.referenceTouchX += commonDeltaRawX;
3348 mPointerGesture.referenceTouchY += commonDeltaRawY;
3349
3350 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3351 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3352
3353 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3354 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3355
3356 mPointerGesture.referenceGestureX += commonDeltaX;
3357 mPointerGesture.referenceGestureY += commonDeltaY;
3358 }
3359
3360 // Report gestures.
3361 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3362 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3363 // PRESS or SWIPE mode.
3364 ALOGD_IF(DEBUG_GESTURES,
3365 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3366 "currentTouchPointerCount=%d",
3367 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3368 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3369
3370 mPointerGesture.currentGestureIdBits.clear();
3371 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3372 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3373 mPointerGesture.currentGestureProperties[0].clear();
3374 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3375 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3376 mPointerGesture.currentGestureCoords[0].clear();
3377 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3378 mPointerGesture.referenceGestureX);
3379 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3380 mPointerGesture.referenceGestureY);
3381 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3382 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3383 float xOffset = static_cast<float>(commonDeltaRawX) /
3384 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3385 float yOffset = static_cast<float>(commonDeltaRawY) /
3386 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3387 mPointerGesture.currentGestureCoords[0]
3388 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3389 mPointerGesture.currentGestureCoords[0]
3390 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3391 }
3392 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3393 // FREEFORM mode.
3394 ALOGD_IF(DEBUG_GESTURES,
3395 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3396 "currentTouchPointerCount=%d",
3397 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3398 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3399
3400 mPointerGesture.currentGestureIdBits.clear();
3401
3402 BitSet32 mappedTouchIdBits;
3403 BitSet32 usedGestureIdBits;
3404 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3405 // Initially, assign the active gesture id to the active touch point
3406 // if there is one. No other touch id bits are mapped yet.
3407 if (!*cancelPreviousGesture) {
3408 mappedTouchIdBits.markBit(activeTouchId);
3409 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3410 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3411 mPointerGesture.activeGestureId;
3412 } else {
3413 mPointerGesture.activeGestureId = -1;
3414 }
3415 } else {
3416 // Otherwise, assume we mapped all touches from the previous frame.
3417 // Reuse all mappings that are still applicable.
3418 mappedTouchIdBits.value =
3419 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3420 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3421
3422 // Check whether we need to choose a new active gesture id because the
3423 // current went went up.
3424 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3425 ~mCurrentCookedState.fingerIdBits.value);
3426 !upTouchIdBits.isEmpty();) {
3427 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3428 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3429 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3430 mPointerGesture.activeGestureId = -1;
3431 break;
3432 }
3433 }
3434 }
3435
3436 ALOGD_IF(DEBUG_GESTURES,
3437 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3438 "activeGestureId=%d",
3439 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3440
3441 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3442 for (uint32_t i = 0; i < currentFingerCount; i++) {
3443 uint32_t touchId = idBits.clearFirstMarkedBit();
3444 uint32_t gestureId;
3445 if (!mappedTouchIdBits.hasBit(touchId)) {
3446 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3447 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3448 ALOGD_IF(DEBUG_GESTURES,
3449 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3450 gestureId);
3451 } else {
3452 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3453 ALOGD_IF(DEBUG_GESTURES,
3454 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3455 touchId, gestureId);
3456 }
3457 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3458 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3459
3460 const RawPointerData::Pointer& pointer =
3461 mCurrentRawState.rawPointerData.pointerForId(touchId);
3462 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3463 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3464 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3465
3466 mPointerGesture.currentGestureProperties[i].clear();
3467 mPointerGesture.currentGestureProperties[i].id = gestureId;
3468 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3469 mPointerGesture.currentGestureCoords[i].clear();
3470 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3471 mPointerGesture.referenceGestureX +
3472 deltaX);
3473 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3474 mPointerGesture.referenceGestureY +
3475 deltaY);
3476 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3477 }
3478
3479 if (mPointerGesture.activeGestureId < 0) {
3480 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3481 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3482 mPointerGesture.activeGestureId);
3483 }
3484 }
3485}
3486
Harry Cutts714d1ad2022-08-24 16:36:43 +00003487void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3488 const RawPointerData::Pointer& currentPointer =
3489 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3490 const RawPointerData::Pointer& lastPointer =
3491 mLastRawState.rawPointerData.pointerForId(pointerId);
3492 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3493 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3494
3495 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3496 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3497
3498 mPointerController->move(deltaX, deltaY);
3499}
3500
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003501std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3502 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003503 mPointerSimple.currentCoords.clear();
3504 mPointerSimple.currentProperties.clear();
3505
3506 bool down, hovering;
3507 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3508 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3509 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003510 mPointerController
3511 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3512 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003513
3514 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3515 down = !hovering;
3516
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003517 float x, y;
3518 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003519 mPointerSimple.currentCoords.copyFrom(
3520 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3521 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3522 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3523 mPointerSimple.currentProperties.id = 0;
3524 mPointerSimple.currentProperties.toolType =
3525 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3526 } else {
3527 down = false;
3528 hovering = false;
3529 }
3530
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003531 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003532}
3533
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003534std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3535 uint32_t policyFlags) {
3536 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003537}
3538
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003539std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3540 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003541 mPointerSimple.currentCoords.clear();
3542 mPointerSimple.currentProperties.clear();
3543
3544 bool down, hovering;
3545 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3546 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003547 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003548 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003549 } else {
3550 mPointerVelocityControl.reset();
3551 }
3552
3553 down = isPointerDown(mCurrentRawState.buttonState);
3554 hovering = !down;
3555
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003556 float x, y;
3557 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003558 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003559 mPointerSimple.currentCoords.copyFrom(
3560 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3561 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3562 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3563 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3564 hovering ? 0.0f : 1.0f);
3565 mPointerSimple.currentProperties.id = 0;
3566 mPointerSimple.currentProperties.toolType =
3567 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3568 } else {
3569 mPointerVelocityControl.reset();
3570
3571 down = false;
3572 hovering = false;
3573 }
3574
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003575 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003576}
3577
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003578std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3579 uint32_t policyFlags) {
3580 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003581
3582 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003583
3584 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003585}
3586
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003587std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3588 uint32_t policyFlags, bool down,
3589 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003590 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3591 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003592 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003593 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003594
3595 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003596 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003597 mPointerController->clearSpots();
3598 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003599 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003600 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003601 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003602 }
Garfield Tan9514d782020-11-10 16:37:23 -08003603 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003604
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003605 float xCursorPosition, yCursorPosition;
3606 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003607
3608 if (mPointerSimple.down && !down) {
3609 mPointerSimple.down = false;
3610
3611 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003612 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3613 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3614 0, metaState, mLastRawState.buttonState,
3615 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3616 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3617 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3618 yCursorPosition, mPointerSimple.downTime,
3619 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003620 }
3621
3622 if (mPointerSimple.hovering && !hovering) {
3623 mPointerSimple.hovering = false;
3624
3625 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003626 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3627 mSource, displayId, policyFlags,
3628 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3629 mLastRawState.buttonState, MotionClassification::NONE,
3630 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3631 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3632 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3633 yCursorPosition, mPointerSimple.downTime,
3634 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003635 }
3636
3637 if (down) {
3638 if (!mPointerSimple.down) {
3639 mPointerSimple.down = true;
3640 mPointerSimple.downTime = when;
3641
3642 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003643 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3644 mSource, displayId, policyFlags,
3645 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3646 mCurrentRawState.buttonState, MotionClassification::NONE,
3647 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3648 &mPointerSimple.currentProperties,
3649 &mPointerSimple.currentCoords, mOrientedXPrecision,
3650 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3651 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003652 }
3653
3654 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003655 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3656 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3657 0, 0, metaState, mCurrentRawState.buttonState,
3658 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3659 &mPointerSimple.currentProperties,
3660 &mPointerSimple.currentCoords, mOrientedXPrecision,
3661 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3662 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003663 }
3664
3665 if (hovering) {
3666 if (!mPointerSimple.hovering) {
3667 mPointerSimple.hovering = true;
3668
3669 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003670 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3671 mSource, displayId, policyFlags,
3672 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3673 mCurrentRawState.buttonState, MotionClassification::NONE,
3674 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3675 &mPointerSimple.currentProperties,
3676 &mPointerSimple.currentCoords, mOrientedXPrecision,
3677 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3678 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003679 }
3680
3681 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003682 out.push_back(
3683 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3684 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3685 metaState, mCurrentRawState.buttonState,
3686 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3687 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3688 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3689 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003690 }
3691
3692 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3693 float vscroll = mCurrentRawState.rawVScroll;
3694 float hscroll = mCurrentRawState.rawHScroll;
3695 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3696 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3697
3698 // Send scroll.
3699 PointerCoords pointerCoords;
3700 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3701 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3702 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3703
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003704 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3705 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3706 0, 0, metaState, mCurrentRawState.buttonState,
3707 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3708 &mPointerSimple.currentProperties, &pointerCoords,
3709 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3710 yCursorPosition, mPointerSimple.downTime,
3711 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003712 }
3713
3714 // Save state.
3715 if (down || hovering) {
3716 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3717 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003718 mPointerSimple.displayId = displayId;
3719 mPointerSimple.source = mSource;
3720 mPointerSimple.lastCursorX = xCursorPosition;
3721 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003722 } else {
3723 mPointerSimple.reset();
3724 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003725 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003726}
3727
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003728std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3729 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003730 std::list<NotifyArgs> out;
3731 if (mPointerSimple.down || mPointerSimple.hovering) {
3732 int32_t metaState = getContext()->getGlobalMetaState();
3733 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3734 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3735 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3736 metaState, mLastRawState.buttonState,
3737 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3738 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3739 mOrientedXPrecision, mOrientedYPrecision,
3740 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3741 mPointerSimple.downTime,
3742 /* videoFrames */ {}));
3743 if (mPointerController != nullptr) {
3744 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3745 }
3746 }
3747 mPointerSimple.reset();
3748 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003749}
3750
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003751NotifyMotionArgs TouchInputMapper::dispatchMotion(
3752 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3753 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003754 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3755 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003756 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003757 PointerCoords pointerCoords[MAX_POINTERS];
3758 PointerProperties pointerProperties[MAX_POINTERS];
3759 uint32_t pointerCount = 0;
3760 while (!idBits.isEmpty()) {
3761 uint32_t id = idBits.clearFirstMarkedBit();
3762 uint32_t index = idToIndex[id];
3763 pointerProperties[pointerCount].copyFrom(properties[index]);
3764 pointerCoords[pointerCount].copyFrom(coords[index]);
3765
3766 if (changedId >= 0 && id == uint32_t(changedId)) {
3767 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3768 }
3769
3770 pointerCount += 1;
3771 }
3772
3773 ALOG_ASSERT(pointerCount != 0);
3774
3775 if (changedId >= 0 && pointerCount == 1) {
3776 // Replace initial down and final up action.
3777 // We can compare the action without masking off the changed pointer index
3778 // because we know the index is 0.
3779 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3780 action = AMOTION_EVENT_ACTION_DOWN;
3781 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003782 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3783 action = AMOTION_EVENT_ACTION_CANCEL;
3784 } else {
3785 action = AMOTION_EVENT_ACTION_UP;
3786 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003787 } else {
3788 // Can't happen.
3789 ALOG_ASSERT(false);
3790 }
3791 }
3792 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3793 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003794 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003795 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003796 }
3797 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3798 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003799 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003800 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003801 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003802 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3803 policyFlags, action, actionButton, flags, metaState, buttonState,
3804 classification, edgeFlags, pointerCount, pointerProperties,
3805 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3806 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003807}
3808
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003809std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3810 std::list<NotifyArgs> out;
3811 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3812 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3813 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003814}
3815
Prabir Pradhan1728b212021-10-19 16:00:03 -07003816bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003817 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003818 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003819 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003820}
3821
3822const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3823 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003824 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3825 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3826 "left=%d, top=%d, right=%d, bottom=%d",
3827 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3828 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003829
3830 if (virtualKey.isHit(x, y)) {
3831 return &virtualKey;
3832 }
3833 }
3834
3835 return nullptr;
3836}
3837
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003838void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3839 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3840 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003841
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003842 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003843
3844 if (currentPointerCount == 0) {
3845 // No pointers to assign.
3846 return;
3847 }
3848
3849 if (lastPointerCount == 0) {
3850 // All pointers are new.
3851 for (uint32_t i = 0; i < currentPointerCount; i++) {
3852 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003853 current.rawPointerData.pointers[i].id = id;
3854 current.rawPointerData.idToIndex[id] = i;
3855 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003856 }
3857 return;
3858 }
3859
3860 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003861 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003862 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003863 uint32_t id = last.rawPointerData.pointers[0].id;
3864 current.rawPointerData.pointers[0].id = id;
3865 current.rawPointerData.idToIndex[id] = 0;
3866 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003867 return;
3868 }
3869
3870 // General case.
3871 // We build a heap of squared euclidean distances between current and last pointers
3872 // associated with the current and last pointer indices. Then, we find the best
3873 // match (by distance) for each current pointer.
3874 // The pointers must have the same tool type but it is possible for them to
3875 // transition from hovering to touching or vice-versa while retaining the same id.
3876 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3877
3878 uint32_t heapSize = 0;
3879 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3880 currentPointerIndex++) {
3881 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3882 lastPointerIndex++) {
3883 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003884 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003885 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003886 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003887 if (currentPointer.toolType == lastPointer.toolType) {
3888 int64_t deltaX = currentPointer.x - lastPointer.x;
3889 int64_t deltaY = currentPointer.y - lastPointer.y;
3890
3891 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3892
3893 // Insert new element into the heap (sift up).
3894 heap[heapSize].currentPointerIndex = currentPointerIndex;
3895 heap[heapSize].lastPointerIndex = lastPointerIndex;
3896 heap[heapSize].distance = distance;
3897 heapSize += 1;
3898 }
3899 }
3900 }
3901
3902 // Heapify
3903 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3904 startIndex -= 1;
3905 for (uint32_t parentIndex = startIndex;;) {
3906 uint32_t childIndex = parentIndex * 2 + 1;
3907 if (childIndex >= heapSize) {
3908 break;
3909 }
3910
3911 if (childIndex + 1 < heapSize &&
3912 heap[childIndex + 1].distance < heap[childIndex].distance) {
3913 childIndex += 1;
3914 }
3915
3916 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3917 break;
3918 }
3919
3920 swap(heap[parentIndex], heap[childIndex]);
3921 parentIndex = childIndex;
3922 }
3923 }
3924
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003925 if (DEBUG_POINTER_ASSIGNMENT) {
3926 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3927 for (size_t i = 0; i < heapSize; i++) {
3928 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3929 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3930 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003931 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003932
3933 // Pull matches out by increasing order of distance.
3934 // To avoid reassigning pointers that have already been matched, the loop keeps track
3935 // of which last and current pointers have been matched using the matchedXXXBits variables.
3936 // It also tracks the used pointer id bits.
3937 BitSet32 matchedLastBits(0);
3938 BitSet32 matchedCurrentBits(0);
3939 BitSet32 usedIdBits(0);
3940 bool first = true;
3941 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3942 while (heapSize > 0) {
3943 if (first) {
3944 // The first time through the loop, we just consume the root element of
3945 // the heap (the one with smallest distance).
3946 first = false;
3947 } else {
3948 // Previous iterations consumed the root element of the heap.
3949 // Pop root element off of the heap (sift down).
3950 heap[0] = heap[heapSize];
3951 for (uint32_t parentIndex = 0;;) {
3952 uint32_t childIndex = parentIndex * 2 + 1;
3953 if (childIndex >= heapSize) {
3954 break;
3955 }
3956
3957 if (childIndex + 1 < heapSize &&
3958 heap[childIndex + 1].distance < heap[childIndex].distance) {
3959 childIndex += 1;
3960 }
3961
3962 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3963 break;
3964 }
3965
3966 swap(heap[parentIndex], heap[childIndex]);
3967 parentIndex = childIndex;
3968 }
3969
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003970 if (DEBUG_POINTER_ASSIGNMENT) {
3971 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3972 for (size_t j = 0; j < heapSize; j++) {
3973 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3974 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3975 heap[j].distance);
3976 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003977 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003978 }
3979
3980 heapSize -= 1;
3981
3982 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3983 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3984
3985 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3986 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3987
3988 matchedCurrentBits.markBit(currentPointerIndex);
3989 matchedLastBits.markBit(lastPointerIndex);
3990
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003991 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3992 current.rawPointerData.pointers[currentPointerIndex].id = id;
3993 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3994 current.rawPointerData.markIdBit(id,
3995 current.rawPointerData.isHovering(
3996 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003997 usedIdBits.markBit(id);
3998
Harry Cutts45483602022-08-24 14:36:48 +00003999 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4000 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4001 ", distance=%" PRIu64,
4002 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004003 break;
4004 }
4005 }
4006
4007 // Assign fresh ids to pointers that were not matched in the process.
4008 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4009 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4010 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4011
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004012 current.rawPointerData.pointers[currentPointerIndex].id = id;
4013 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4014 current.rawPointerData.markIdBit(id,
4015 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004016
Harry Cutts45483602022-08-24 14:36:48 +00004017 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4018 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4019 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004020 }
4021}
4022
4023int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4024 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4025 return AKEY_STATE_VIRTUAL;
4026 }
4027
4028 for (const VirtualKey& virtualKey : mVirtualKeys) {
4029 if (virtualKey.keyCode == keyCode) {
4030 return AKEY_STATE_UP;
4031 }
4032 }
4033
4034 return AKEY_STATE_UNKNOWN;
4035}
4036
4037int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4038 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4039 return AKEY_STATE_VIRTUAL;
4040 }
4041
4042 for (const VirtualKey& virtualKey : mVirtualKeys) {
4043 if (virtualKey.scanCode == scanCode) {
4044 return AKEY_STATE_UP;
4045 }
4046 }
4047
4048 return AKEY_STATE_UNKNOWN;
4049}
4050
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004051bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4052 const std::vector<int32_t>& keyCodes,
4053 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004054 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004055 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004056 if (virtualKey.keyCode == keyCodes[i]) {
4057 outFlags[i] = 1;
4058 }
4059 }
4060 }
4061
4062 return true;
4063}
4064
4065std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4066 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004067 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004068 return std::make_optional(mPointerController->getDisplayId());
4069 } else {
4070 return std::make_optional(mViewport.displayId);
4071 }
4072 }
4073 return std::nullopt;
4074}
4075
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004076} // namespace android