blob: 9b2cf029da135152e09c2f851741f6f8e08cff8a [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 Pradhane04ffaa2022-12-13 23:04:04 +000058static std::string toString(const InputDeviceUsiVersion& v) {
59 return base::StringPrintf("%d.%d", v.majorVersion, v.minorVersion);
60}
61
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070062template <typename T>
63inline static void swap(T& a, T& b) {
64 T temp = a;
65 a = b;
66 b = temp;
67}
68
69static float calculateCommonVector(float a, float b) {
70 if (a > 0 && b > 0) {
71 return a < b ? a : b;
72 } else if (a < 0 && b < 0) {
73 return a > b ? a : b;
74 } else {
75 return 0;
76 }
77}
78
79inline static float distance(float x1, float y1, float x2, float y2) {
80 return hypotf(x1 - x2, y1 - y2);
81}
82
83inline static int32_t signExtendNybble(int32_t value) {
84 return value >= 8 ? value - 16 : value;
85}
86
Prabir Pradhan675f25a2022-11-10 22:04:07 +000087static ui::Size getNaturalDisplaySize(const DisplayViewport& viewport) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000088 ui::Size rotatedDisplaySize{viewport.deviceWidth, viewport.deviceHeight};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +000089 if (viewport.orientation == ui::ROTATION_90 || viewport.orientation == ui::ROTATION_270) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000090 std::swap(rotatedDisplaySize.width, rotatedDisplaySize.height);
91 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +000092 return rotatedDisplaySize;
Prabir Pradhan2d613f42022-11-10 20:22:06 +000093}
94
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +000095static int32_t filterButtonState(InputReaderConfiguration& config, int32_t buttonState) {
96 if (!config.stylusButtonMotionEventsEnabled) {
97 buttonState &=
98 ~(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY | AMOTION_EVENT_BUTTON_STYLUS_SECONDARY);
99 }
100 return buttonState;
101}
102
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700103// --- RawPointerData ---
104
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700105void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
106 float x = 0, y = 0;
107 uint32_t count = touchingIdBits.count();
108 if (count) {
109 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
110 uint32_t id = idBits.clearFirstMarkedBit();
111 const Pointer& pointer = pointerForId(id);
112 x += pointer.x;
113 y += pointer.y;
114 }
115 x /= count;
116 y /= count;
117 }
118 *outX = x;
119 *outY = y;
120}
121
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700122// --- TouchInputMapper ---
123
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800124TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
125 : InputMapper(deviceContext),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000126 mTouchButtonAccumulator(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700127 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100128 mDeviceMode(DeviceMode::DISABLED),
Michael Wrighta9cf4192022-12-01 23:46:39 +0000129 mInputDeviceOrientation(ui::ROTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700130
131TouchInputMapper::~TouchInputMapper() {}
132
Philip Junker4af3b3d2021-12-14 10:36:55 +0100133uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700134 return mSource;
135}
136
137void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
138 InputMapper::populateDeviceInfo(info);
139
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000140 if (mDeviceMode == DeviceMode::DISABLED) {
141 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700142 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000143
144 info->addMotionRange(mOrientedRanges.x);
145 info->addMotionRange(mOrientedRanges.y);
146 info->addMotionRange(mOrientedRanges.pressure);
147
148 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
149 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
150 //
151 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
152 // motion, i.e. the hardware dimensions, as the finger could move completely across the
153 // touchpad in one sample cycle.
154 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
155 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
156 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
157 x.resolution);
158 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
159 y.resolution);
160 }
161
162 if (mOrientedRanges.size) {
163 info->addMotionRange(*mOrientedRanges.size);
164 }
165
166 if (mOrientedRanges.touchMajor) {
167 info->addMotionRange(*mOrientedRanges.touchMajor);
168 info->addMotionRange(*mOrientedRanges.touchMinor);
169 }
170
171 if (mOrientedRanges.toolMajor) {
172 info->addMotionRange(*mOrientedRanges.toolMajor);
173 info->addMotionRange(*mOrientedRanges.toolMinor);
174 }
175
176 if (mOrientedRanges.orientation) {
177 info->addMotionRange(*mOrientedRanges.orientation);
178 }
179
180 if (mOrientedRanges.distance) {
181 info->addMotionRange(*mOrientedRanges.distance);
182 }
183
184 if (mOrientedRanges.tilt) {
185 info->addMotionRange(*mOrientedRanges.tilt);
186 }
187
188 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
189 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
190 }
191 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
192 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
193 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000194 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000195 info->setUsiVersion(mParameters.usiVersion);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700196}
197
198void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700199 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800200 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700201 dumpParameters(dump);
202 dumpVirtualKeys(dump);
203 dumpRawPointerAxes(dump);
204 dumpCalibration(dump);
205 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700206 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700207
208 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000209 mRawToDisplay.dump(dump, "RawToDisplay Transform:", INDENT4);
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000210 mRawRotation.dump(dump, "RawRotation Transform:", INDENT4);
211 dump += StringPrintf(INDENT4 "OrientedXPrecision: %0.3f\n", mOrientedXPrecision);
212 dump += StringPrintf(INDENT4 "OrientedYPrecision: %0.3f\n", mOrientedYPrecision);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700213 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
214 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
215 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
216 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
217 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
218 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
219 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
220 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
221 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
222 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
223
224 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
225 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
226 mLastRawState.rawPointerData.pointerCount);
227 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
228 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
229 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
230 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
231 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
232 "toolType=%d, isHovering=%s\n",
233 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
234 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
235 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
236 pointer.distance, pointer.toolType, toString(pointer.isHovering));
237 }
238
239 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
240 mLastCookedState.buttonState);
241 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
242 mLastCookedState.cookedPointerData.pointerCount);
243 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
244 const PointerProperties& pointerProperties =
245 mLastCookedState.cookedPointerData.pointerProperties[i];
246 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000247 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
248 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
249 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700250 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
251 "toolType=%d, isHovering=%s\n",
252 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000253 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
254 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700255 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
256 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
257 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
258 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
259 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
260 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
261 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
262 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
263 pointerProperties.toolType,
264 toString(mLastCookedState.cookedPointerData.isHovering(i)));
265 }
266
267 dump += INDENT3 "Stylus Fusion:\n";
268 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
269 toString(mExternalStylusConnected));
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000270 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
271 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700272 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
273 mExternalStylusFusionTimeout);
Prabir Pradhan124ea442022-10-28 20:27:44 +0000274 dump += StringPrintf(INDENT4 " External Stylus Buttons Applied: 0x%08x",
275 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700276 dump += INDENT3 "External Stylus State:\n";
277 dumpStylusState(dump, mExternalStylusState);
278
Michael Wright227c5542020-07-02 18:30:52 +0100279 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700280 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
281 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
282 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
283 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
284 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
285 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
286 }
287}
288
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700289std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
290 const InputReaderConfiguration* config,
291 uint32_t changes) {
292 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700293
294 mConfig = *config;
295
296 if (!changes) { // first time only
297 // Configure basic parameters.
298 configureParameters();
299
300 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800301 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000302 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700303
304 // Configure absolute axis information.
305 configureRawPointerAxes();
306
307 // Prepare input device calibration.
308 parseCalibration();
309 resolveCalibration();
310 }
311
312 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
313 // Update location calibration to reflect current settings
314 updateAffineTransformation();
315 }
316
317 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
318 // Update pointer speed.
319 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
320 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
321 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
322 }
323
324 bool resetNeeded = false;
325 if (!changes ||
326 (changes &
327 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800328 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700329 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
330 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
331 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700332 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700333 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700334 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700335 }
336
337 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700338 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000339
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700340 // Send reset, unless this is the first time the device has been configured,
341 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000342 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700343 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700344 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700345}
346
347void TouchInputMapper::resolveExternalStylusPresence() {
348 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800349 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700350 mExternalStylusConnected = !devices.empty();
351
352 if (!mExternalStylusConnected) {
353 resetExternalStylus();
354 }
355}
356
357void TouchInputMapper::configureParameters() {
358 // Use the pointer presentation mode for devices that do not support distinct
359 // multitouch. The spot-based presentation relies on being able to accurately
360 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800361 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100362 ? Parameters::GestureMode::SINGLE_TOUCH
363 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700364
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700365 std::string gestureModeString;
366 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800367 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700368 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100369 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700370 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100371 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700372 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700373 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700374 }
375 }
376
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000377 configureDeviceType();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700378
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800379 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700380
Michael Wright227c5542020-07-02 18:30:52 +0100381 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700382 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800383 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700384
Michael Wrighta9cf4192022-12-01 23:46:39 +0000385 mParameters.orientation = ui::ROTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700386 std::string orientationString;
387 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700388 orientationString)) {
389 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
390 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
391 } else if (orientationString == "ORIENTATION_90") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000392 mParameters.orientation = ui::ROTATION_90;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700393 } else if (orientationString == "ORIENTATION_180") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000394 mParameters.orientation = ui::ROTATION_180;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700395 } else if (orientationString == "ORIENTATION_270") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000396 mParameters.orientation = ui::ROTATION_270;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700397 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700398 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700399 }
400 }
401
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700402 mParameters.hasAssociatedDisplay = false;
403 mParameters.associatedDisplayIsExternal = false;
404 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100405 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000406 mParameters.deviceType == Parameters::DeviceType::POINTER ||
407 (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
408 getDeviceContext().getAssociatedViewport())) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700409 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100410 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800411 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700412 std::string uniqueDisplayId;
413 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800414 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700415 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
416 }
417 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800418 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700419 mParameters.hasAssociatedDisplay = true;
420 }
421
422 // Initial downs on external touch devices should wake the device.
423 // Normally we don't do this for internal touch screens to prevent them from waking
424 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800425 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700426 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000427
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000428 InputDeviceUsiVersion usiVersion;
429 if (getDeviceContext().getConfiguration().tryGetProperty("touch.usiVersionMajor",
430 usiVersion.majorVersion) &&
431 getDeviceContext().getConfiguration().tryGetProperty("touch.usiVersionMinor",
432 usiVersion.minorVersion)) {
433 mParameters.usiVersion = usiVersion;
434 }
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700435
436 mParameters.enableForInactiveViewport = false;
437 getDeviceContext().getConfiguration().tryGetProperty("touch.enableForInactiveViewport",
438 mParameters.enableForInactiveViewport);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700439}
440
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000441void TouchInputMapper::configureDeviceType() {
442 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
443 // The device is a touch screen.
444 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
445 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
446 // The device is a pointing device like a track pad.
447 mParameters.deviceType = Parameters::DeviceType::POINTER;
448 } else {
449 // The device is a touch pad of unknown purpose.
450 mParameters.deviceType = Parameters::DeviceType::POINTER;
451 }
452
453 // Type association takes precedence over the device type found in the idc file.
454 std::string deviceTypeString = getDeviceContext().getDeviceTypeAssociation().value_or("");
455 if (deviceTypeString.empty()) {
456 getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType", deviceTypeString);
457 }
458 if (deviceTypeString == "touchScreen") {
459 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
460 } else if (deviceTypeString == "touchNavigation") {
461 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
462 } else if (deviceTypeString == "pointer") {
463 mParameters.deviceType = Parameters::DeviceType::POINTER;
464 } else if (deviceTypeString != "default" && deviceTypeString != "") {
465 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
466 }
467}
468
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700469void TouchInputMapper::dumpParameters(std::string& dump) {
470 dump += INDENT3 "Parameters:\n";
471
Dominik Laskowski75788452021-02-09 18:51:25 -0800472 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700473
Dominik Laskowski75788452021-02-09 18:51:25 -0800474 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700475
476 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
477 "displayId='%s'\n",
478 toString(mParameters.hasAssociatedDisplay),
479 toString(mParameters.associatedDisplayIsExternal),
480 mParameters.uniqueDisplayId.c_str());
481 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800482 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000483 dump += StringPrintf(INDENT4 "UsiVersion: %s\n",
484 toString(mParameters.usiVersion, toString).c_str());
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700485 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
486 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700487}
488
489void TouchInputMapper::configureRawPointerAxes() {
490 mRawPointerAxes.clear();
491}
492
493void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
494 dump += INDENT3 "Raw Touch Axes:\n";
495 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
496 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
497 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
498 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
499 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
500 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
501 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
502 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
503 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
504 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
505 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
506 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
507 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
508}
509
510bool TouchInputMapper::hasExternalStylus() const {
511 return mExternalStylusConnected;
512}
513
514/**
515 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000516 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800517 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000518 * 3. Get the matching viewport by either unique id in idc file or by the display type
519 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800520 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700521 */
522std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800523 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000524 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800525 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700526 }
527
Christine Franks2a2293c2022-01-18 11:51:16 -0800528 const std::optional<std::string> associatedDisplayUniqueId =
529 getDeviceContext().getAssociatedDisplayUniqueId();
530 if (associatedDisplayUniqueId) {
531 return getDeviceContext().getAssociatedViewport();
532 }
533
Michael Wright227c5542020-07-02 18:30:52 +0100534 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800535 std::optional<DisplayViewport> viewport =
536 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
537 if (viewport) {
538 return viewport;
539 } else {
540 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
541 mConfig.defaultPointerDisplayId);
542 }
543 }
544
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700545 // Check if uniqueDisplayId is specified in idc file.
546 if (!mParameters.uniqueDisplayId.empty()) {
547 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
548 }
549
550 ViewportType viewportTypeToUse;
551 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100552 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700553 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100554 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700555 }
556
557 std::optional<DisplayViewport> viewport =
558 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100559 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700560 ALOGW("Input device %s should be associated with external display, "
561 "fallback to internal one for the external viewport is not found.",
562 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100563 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700564 }
565
566 return viewport;
567 }
568
569 // No associated display, return a non-display viewport.
570 DisplayViewport newViewport;
571 // Raw width and height in the natural orientation.
572 int32_t rawWidth = mRawPointerAxes.getRawWidth();
573 int32_t rawHeight = mRawPointerAxes.getRawHeight();
574 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
575 return std::make_optional(newViewport);
576}
577
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800578int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
579 if (resolution < 0) {
580 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
581 getDeviceName().c_str());
582 return 0;
583 }
584 return resolution;
585}
586
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800587void TouchInputMapper::initializeSizeRanges() {
588 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
589 mSizeScale = 0.0f;
590 return;
591 }
592
593 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000594 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800595
596 // Size factors.
597 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
598 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
599 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
600 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
601 } else {
602 mSizeScale = 0.0f;
603 }
604
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700605 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
606 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
607 .source = mSource,
608 .min = 0,
609 .max = diagonalSize,
610 .flat = 0,
611 .fuzz = 0,
612 .resolution = 0,
613 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800614
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800615 if (mRawPointerAxes.touchMajor.valid) {
616 mRawPointerAxes.touchMajor.resolution =
617 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700618 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800619 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800620
621 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700622 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800623 if (mRawPointerAxes.touchMinor.valid) {
624 mRawPointerAxes.touchMinor.resolution =
625 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700626 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800627 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800628
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700629 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
630 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
631 .source = mSource,
632 .min = 0,
633 .max = diagonalSize,
634 .flat = 0,
635 .fuzz = 0,
636 .resolution = 0,
637 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800638 if (mRawPointerAxes.toolMajor.valid) {
639 mRawPointerAxes.toolMajor.resolution =
640 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700641 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800642 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800643
644 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700645 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800646 if (mRawPointerAxes.toolMinor.valid) {
647 mRawPointerAxes.toolMinor.resolution =
648 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700649 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800650 }
651
652 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700653 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
654 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
655 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
656 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800657 } else {
658 // Support for other calibrations can be added here.
659 ALOGW("%s calibration is not supported for size ranges at the moment. "
660 "Using raw resolution instead",
661 ftl::enum_string(mCalibration.sizeCalibration).c_str());
662 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800663
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700664 mOrientedRanges.size = InputDeviceInfo::MotionRange{
665 .axis = AMOTION_EVENT_AXIS_SIZE,
666 .source = mSource,
667 .min = 0,
668 .max = 1.0,
669 .flat = 0,
670 .fuzz = 0,
671 .resolution = 0,
672 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800673}
674
675void TouchInputMapper::initializeOrientedRanges() {
676 // Configure X and Y factors.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000677 const float orientedScaleX = mRawToDisplay.getScaleX();
678 const float orientedScaleY = mRawToDisplay.getScaleY();
679 mOrientedXPrecision = 1.0f / orientedScaleX;
680 mOrientedYPrecision = 1.0f / orientedScaleY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800681
682 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
683 mOrientedRanges.x.source = mSource;
684 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
685 mOrientedRanges.y.source = mSource;
686
687 // Scale factor for terms that are not oriented in a particular axis.
688 // If the pixels are square then xScale == yScale otherwise we fake it
689 // by choosing an average.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000690 mGeometricScale = avg(orientedScaleX, orientedScaleY);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800691
692 initializeSizeRanges();
693
694 // Pressure factors.
695 mPressureScale = 0;
696 float pressureMax = 1.0;
697 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
698 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700699 if (mCalibration.pressureScale) {
700 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800701 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
702 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
703 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
704 }
705 }
706
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700707 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
708 .axis = AMOTION_EVENT_AXIS_PRESSURE,
709 .source = mSource,
710 .min = 0,
711 .max = pressureMax,
712 .flat = 0,
713 .fuzz = 0,
714 .resolution = 0,
715 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800716
717 // Tilt
718 mTiltXCenter = 0;
719 mTiltXScale = 0;
720 mTiltYCenter = 0;
721 mTiltYScale = 0;
722 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
723 if (mHaveTilt) {
724 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
725 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
726 mTiltXScale = M_PI / 180;
727 mTiltYScale = M_PI / 180;
728
729 if (mRawPointerAxes.tiltX.resolution) {
730 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
731 }
732 if (mRawPointerAxes.tiltY.resolution) {
733 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
734 }
735
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700736 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
737 .axis = AMOTION_EVENT_AXIS_TILT,
738 .source = mSource,
739 .min = 0,
740 .max = M_PI_2,
741 .flat = 0,
742 .fuzz = 0,
743 .resolution = 0,
744 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800745 }
746
747 // Orientation
748 mOrientationScale = 0;
749 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700750 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
751 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
752 .source = mSource,
753 .min = -M_PI,
754 .max = M_PI,
755 .flat = 0,
756 .fuzz = 0,
757 .resolution = 0,
758 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800759
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800760 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
761 if (mCalibration.orientationCalibration ==
762 Calibration::OrientationCalibration::INTERPOLATED) {
763 if (mRawPointerAxes.orientation.valid) {
764 if (mRawPointerAxes.orientation.maxValue > 0) {
765 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
766 } else if (mRawPointerAxes.orientation.minValue < 0) {
767 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
768 } else {
769 mOrientationScale = 0;
770 }
771 }
772 }
773
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700774 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
775 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
776 .source = mSource,
777 .min = -M_PI_2,
778 .max = M_PI_2,
779 .flat = 0,
780 .fuzz = 0,
781 .resolution = 0,
782 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800783 }
784
785 // Distance
786 mDistanceScale = 0;
787 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
788 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700789 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800790 }
791
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700792 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800793
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700794 .axis = AMOTION_EVENT_AXIS_DISTANCE,
795 .source = mSource,
796 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
797 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
798 .flat = 0,
799 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
800 .resolution = 0,
801 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800802 }
803
804 // Compute oriented precision, scales and ranges.
805 // Note that the maximum value reported is an inclusive maximum value so it is one
806 // unit less than the total width or height of the display.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000807 // TODO(b/20508709): Calculate the oriented ranges using the input device's raw frame.
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800808 switch (mInputDeviceOrientation) {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000809 case ui::ROTATION_90:
810 case ui::ROTATION_270:
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800811 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000812 mOrientedRanges.x.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800813 mOrientedRanges.x.flat = 0;
814 mOrientedRanges.x.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000815 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mRawToDisplay.getScaleY();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800816
817 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000818 mOrientedRanges.y.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800819 mOrientedRanges.y.flat = 0;
820 mOrientedRanges.y.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000821 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mRawToDisplay.getScaleX();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800822 break;
823
824 default:
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800825 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000826 mOrientedRanges.x.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800827 mOrientedRanges.x.flat = 0;
828 mOrientedRanges.x.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000829 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mRawToDisplay.getScaleX();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800830
831 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000832 mOrientedRanges.y.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800833 mOrientedRanges.y.flat = 0;
834 mOrientedRanges.y.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000835 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mRawToDisplay.getScaleY();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800836 break;
837 }
838}
839
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000840void TouchInputMapper::computeInputTransforms() {
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000841 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
842
843 ui::Size rotatedRawSize = rawSize;
844 if (mInputDeviceOrientation == ui::ROTATION_270 || mInputDeviceOrientation == ui::ROTATION_90) {
845 std::swap(rotatedRawSize.width, rotatedRawSize.height);
846 }
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000847 const auto rotationFlags = ui::Transform::toRotationFlags(-mInputDeviceOrientation);
848 mRawRotation = ui::Transform{rotationFlags};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000849
850 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
851 ui::Transform undoRawOffset;
852 undoRawOffset.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
853
854 // Step 2: Rotate the raw coordinates to the expected orientation.
855 ui::Transform rotate;
856 // When rotating raw coordinates, the raw size will be used as an offset.
857 // Account for the extra unit added to the raw range when the raw size was calculated.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000858 rotate.set(rotationFlags, rotatedRawSize.width - 1, rotatedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000859
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;
887 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800888 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700889 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100890 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700891 if (hasStylus()) {
892 mSource |= AINPUT_SOURCE_STYLUS;
893 }
894 if (hasExternalStylus()) {
895 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
896 }
Michael Wright227c5542020-07-02 18:30:52 +0100897 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700898 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100899 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700900 } else {
901 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100902 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700903 }
904
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000905 const std::optional<DisplayViewport> newViewportOpt = findViewport();
906
907 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700908 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
909 ALOGW("Touch device '%s' did not report support for X or Y axis! "
910 "The device will be inoperable.",
911 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100912 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000913 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700914 ALOGI("Touch device '%s' could not query the properties of its associated "
915 "display. The device will be inoperable until the display size "
916 "becomes available.",
917 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100918 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700919 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000920 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
921 getDeviceName().c_str(), getDeviceId());
922 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000923 }
924
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700925 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000926 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000927 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
928 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
929 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
930 const float rawMeanResolution =
931 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700932
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000933 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
934 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700935 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700936 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000937 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
938 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
939 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700940
Michael Wright227c5542020-07-02 18:30:52 +0100941 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000942 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700943
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000944 mDisplayBounds = getNaturalDisplaySize(mViewport);
945 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
946 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700947
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000948 // InputReader works in the un-rotated display coordinate space, so we don't need to do
949 // anything if the device is already orientation-aware. If the device is not
950 // orientation-aware, then we need to apply the inverse rotation of the display so that
951 // when the display rotation is applied later as a part of the per-window transform, we
952 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700953 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +0000954 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000955 : getInverseRotation(mViewport.orientation);
956 // For orientation-aware devices that work in the un-rotated coordinate space, the
957 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000958 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000959 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700960
961 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +0000962 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000963 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700964 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000965 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000966 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +0000967 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000968 mRawToDisplay.reset();
969 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000970 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700971 }
972 }
973
974 // If moving between pointer modes, need to reset some state.
975 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
976 if (deviceModeChanged) {
977 mOrientedRanges.clear();
978 }
979
Seunghwan Choi2de48e42023-01-17 20:45:15 +0900980 // Create and preserve the pointer controller in the following cases:
981 const bool isPointerControllerNeeded =
982 // - when the device is in pointer mode, to show the mouse cursor;
983 (mDeviceMode == DeviceMode::POINTER) ||
984 // - when pointer capture is enabled, to preserve the mouse cursor position;
985 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
986 mConfig.pointerCaptureRequest.enable) ||
987 // - when we should be showing touches;
988 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
989 // - when we should be showing a pointer icon for direct styluses.
990 (mDeviceMode == DeviceMode::DIRECT && mConfig.stylusPointerIconEnabled && hasStylus());
991 if (isPointerControllerNeeded) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800992 if (mPointerController == nullptr) {
993 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700994 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000995 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800996 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
997 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700998 } else {
lilinnandef700b2022-06-17 19:32:01 +0800999 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1000 !mConfig.showTouches) {
1001 mPointerController->clearSpots();
1002 }
Michael Wright17db18e2020-06-26 20:51:44 +01001003 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001004 }
1005
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001006 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001007 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001008 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001009 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001010 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001011
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001012 configureVirtualKeys();
1013
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001014 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001015
1016 // Location
1017 updateAffineTransformation();
1018
Michael Wright227c5542020-07-02 18:30:52 +01001019 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001020 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001021 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1022 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001023
1024 // Scale movements such that one whole swipe of the touch pad covers a
1025 // given area relative to the diagonal size of the display when no acceleration
1026 // is applied.
1027 // Assume that the touch pad has a square aspect ratio such that movements in
1028 // X and Y of the same number of raw units cover the same physical distance.
1029 mPointerXMovementScale =
1030 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1031 mPointerYMovementScale = mPointerXMovementScale;
1032
1033 // Scale zooms to cover a smaller range of the display than movements do.
1034 // This value determines the area around the pointer that is affected by freeform
1035 // pointer gestures.
1036 mPointerXZoomScale =
1037 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1038 mPointerYZoomScale = mPointerXZoomScale;
1039
HQ Liue6983c72022-04-19 22:14:56 +00001040 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1041 // axis is non positive value.
1042 const float minFreeformGestureWidth =
1043 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1044
1045 mPointerGestureMaxSwipeWidth =
1046 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1047 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001048 }
1049
1050 // Inform the dispatcher about the changes.
1051 *outResetNeeded = true;
1052 bumpGeneration();
1053 }
1054}
1055
Prabir Pradhan1728b212021-10-19 16:00:03 -07001056void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001057 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001058 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001059 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1060 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001061 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001062}
1063
1064void TouchInputMapper::configureVirtualKeys() {
1065 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001066 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001067
1068 mVirtualKeys.clear();
1069
1070 if (virtualKeyDefinitions.size() == 0) {
1071 return;
1072 }
1073
1074 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1075 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1076 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1077 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1078
1079 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1080 VirtualKey virtualKey;
1081
1082 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1083 int32_t keyCode;
1084 int32_t dummyKeyMetaState;
1085 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001086 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1087 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001088 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1089 continue; // drop the key
1090 }
1091
1092 virtualKey.keyCode = keyCode;
1093 virtualKey.flags = flags;
1094
1095 // convert the key definition's display coordinates into touch coordinates for a hit box
1096 int32_t halfWidth = virtualKeyDefinition.width / 2;
1097 int32_t halfHeight = virtualKeyDefinition.height / 2;
1098
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001099 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1100 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001101 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001102 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1103 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001104 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001105 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1106 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001107 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001108 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1109 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001110 touchScreenTop;
1111 mVirtualKeys.push_back(virtualKey);
1112 }
1113}
1114
1115void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1116 if (!mVirtualKeys.empty()) {
1117 dump += INDENT3 "Virtual Keys:\n";
1118
1119 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1120 const VirtualKey& virtualKey = mVirtualKeys[i];
1121 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1122 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1123 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1124 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1125 }
1126 }
1127}
1128
1129void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001130 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001131 Calibration& out = mCalibration;
1132
1133 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001134 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001135 std::string sizeCalibrationString;
1136 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001137 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001138 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001140 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001141 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001142 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001143 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001144 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001146 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001148 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001149 }
1150 }
1151
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001152 float sizeScale;
1153
1154 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1155 out.sizeScale = sizeScale;
1156 }
1157 float sizeBias;
1158 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1159 out.sizeBias = sizeBias;
1160 }
1161 bool sizeIsSummed;
1162 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1163 out.sizeIsSummed = sizeIsSummed;
1164 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001165
1166 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001167 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001168 std::string pressureCalibrationString;
1169 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001173 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001175 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 } else if (pressureCalibrationString != "default") {
1177 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001178 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001179 }
1180 }
1181
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001182 float pressureScale;
1183 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1184 out.pressureScale = pressureScale;
1185 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001186
1187 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001188 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001189 std::string orientationCalibrationString;
1190 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001191 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001192 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001194 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001195 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001196 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001197 } else if (orientationCalibrationString != "default") {
1198 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001199 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001200 }
1201 }
1202
1203 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001204 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001205 std::string distanceCalibrationString;
1206 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001207 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001208 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001209 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001210 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211 } else if (distanceCalibrationString != "default") {
1212 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001213 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214 }
1215 }
1216
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001217 float distanceScale;
1218 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1219 out.distanceScale = distanceScale;
1220 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001221}
1222
1223void TouchInputMapper::resolveCalibration() {
1224 // Size
1225 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001226 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1227 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001228 }
1229 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001230 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001231 }
1232
1233 // Pressure
1234 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001235 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1236 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001237 }
1238 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001239 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001240 }
1241
1242 // Orientation
1243 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001244 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1245 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001246 }
1247 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001248 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001249 }
1250
1251 // Distance
1252 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001253 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1254 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001255 }
1256 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001257 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001258 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001259}
1260
1261void TouchInputMapper::dumpCalibration(std::string& dump) {
1262 dump += INDENT3 "Calibration:\n";
1263
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001264 dump += INDENT4 "touch.size.calibration: ";
1265 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001266
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001267 if (mCalibration.sizeScale) {
1268 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001269 }
1270
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001271 if (mCalibration.sizeBias) {
1272 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001273 }
1274
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001275 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001276 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001277 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001278 }
1279
1280 // Pressure
1281 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001282 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001283 dump += INDENT4 "touch.pressure.calibration: none\n";
1284 break;
Michael Wright227c5542020-07-02 18:30:52 +01001285 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001286 dump += INDENT4 "touch.pressure.calibration: physical\n";
1287 break;
Michael Wright227c5542020-07-02 18:30:52 +01001288 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001289 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1290 break;
1291 default:
1292 ALOG_ASSERT(false);
1293 }
1294
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001295 if (mCalibration.pressureScale) {
1296 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001297 }
1298
1299 // Orientation
1300 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001301 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001302 dump += INDENT4 "touch.orientation.calibration: none\n";
1303 break;
Michael Wright227c5542020-07-02 18:30:52 +01001304 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001305 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1306 break;
Michael Wright227c5542020-07-02 18:30:52 +01001307 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001308 dump += INDENT4 "touch.orientation.calibration: vector\n";
1309 break;
1310 default:
1311 ALOG_ASSERT(false);
1312 }
1313
1314 // Distance
1315 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001316 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001317 dump += INDENT4 "touch.distance.calibration: none\n";
1318 break;
Michael Wright227c5542020-07-02 18:30:52 +01001319 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001320 dump += INDENT4 "touch.distance.calibration: scaled\n";
1321 break;
1322 default:
1323 ALOG_ASSERT(false);
1324 }
1325
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001326 if (mCalibration.distanceScale) {
1327 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001328 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001329}
1330
1331void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1332 dump += INDENT3 "Affine Transformation:\n";
1333
1334 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1335 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1336 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1337 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1338 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1339 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1340}
1341
1342void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001343 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001344 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001345}
1346
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001347std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001348 std::list<NotifyArgs> out = cancelTouch(when, when);
1349 updateTouchSpots();
1350
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001351 mCursorButtonAccumulator.reset(getDeviceContext());
1352 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001353 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001354
1355 mPointerVelocityControl.reset();
1356 mWheelXVelocityControl.reset();
1357 mWheelYVelocityControl.reset();
1358
1359 mRawStatesPending.clear();
1360 mCurrentRawState.clear();
1361 mCurrentCookedState.clear();
1362 mLastRawState.clear();
1363 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001364 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001365 mSentHoverEnter = false;
1366 mHavePointerIds = false;
1367 mCurrentMotionAborted = false;
1368 mDownTime = 0;
1369
1370 mCurrentVirtualKey.down = false;
1371
1372 mPointerGesture.reset();
1373 mPointerSimple.reset();
1374 resetExternalStylus();
1375
1376 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001377 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001378 mPointerController->clearSpots();
1379 }
1380
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001381 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001382}
1383
1384void TouchInputMapper::resetExternalStylus() {
1385 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001386 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001387 mExternalStylusFusionTimeout = LLONG_MAX;
1388 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001389 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001390}
1391
1392void TouchInputMapper::clearStylusDataPendingFlags() {
1393 mExternalStylusDataPending = false;
1394 mExternalStylusFusionTimeout = LLONG_MAX;
1395}
1396
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001397std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001398 mCursorButtonAccumulator.process(rawEvent);
1399 mCursorScrollAccumulator.process(rawEvent);
1400 mTouchButtonAccumulator.process(rawEvent);
1401
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001402 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001403 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001404 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001405 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001406 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001407}
1408
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001409std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1410 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001411 if (mDeviceMode == DeviceMode::DISABLED) {
1412 // Only save the last pending state when the device is disabled.
1413 mRawStatesPending.clear();
1414 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001415 // Push a new state.
1416 mRawStatesPending.emplace_back();
1417
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001418 RawState& next = mRawStatesPending.back();
1419 next.clear();
1420 next.when = when;
1421 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001422
1423 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001424 next.buttonState = filterButtonState(mConfig,
1425 mTouchButtonAccumulator.getButtonState() |
1426 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001427
1428 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001429 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1430 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001431 mCursorScrollAccumulator.finishSync();
1432
1433 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001434 syncTouch(when, &next);
1435
1436 // The last RawState is the actually second to last, since we just added a new state
1437 const RawState& last =
1438 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001439
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001440 std::tie(next.when, next.readTime) =
1441 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1442 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001443
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001444 // Assign pointer ids.
1445 if (!mHavePointerIds) {
1446 assignPointerIds(last, next);
1447 }
1448
Harry Cutts45483602022-08-24 14:36:48 +00001449 ALOGD_IF(DEBUG_RAW_EVENTS,
1450 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1451 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1452 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1453 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1454 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1455 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001456
Arthur Hung9ad18942021-06-19 02:04:46 +00001457 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1458 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1459 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1460 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1461 next.rawPointerData.hoveringIdBits.value);
1462 }
1463
Harry Cutts33476232023-01-30 19:57:29 +00001464 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001465 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001466}
1467
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001468std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1469 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001470 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001471 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001472 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001473 }
1474
1475 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1476 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1477 // touching the current state will only observe the events that have been dispatched to the
1478 // rest of the pipeline.
1479 const size_t N = mRawStatesPending.size();
1480 size_t count;
1481 for (count = 0; count < N; count++) {
1482 const RawState& next = mRawStatesPending[count];
1483
1484 // A failure to assign the stylus id means that we're waiting on stylus data
1485 // and so should defer the rest of the pipeline.
1486 if (assignExternalStylusId(next, timeout)) {
1487 break;
1488 }
1489
1490 // All ready to go.
1491 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001492 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001493 if (mCurrentRawState.when < mLastRawState.when) {
1494 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001495 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001496 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001497 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001498 }
1499 if (count != 0) {
1500 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1501 }
1502
1503 if (mExternalStylusDataPending) {
1504 if (timeout) {
1505 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1506 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001507 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001508 ALOGD_IF(DEBUG_STYLUS_FUSION,
1509 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001510 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001511 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001512 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1513 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1514 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1515 }
1516 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001517 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001518}
1519
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001520std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1521 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001522 // Always start with a clean state.
1523 mCurrentCookedState.clear();
1524
1525 // Apply stylus buttons to current raw state.
1526 applyExternalStylusButtonState(when);
1527
1528 // Handle policy on initial down or hover events.
1529 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1530 mCurrentRawState.rawPointerData.pointerCount != 0;
1531
1532 uint32_t policyFlags = 0;
1533 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1534 if (initialDown || buttonsPressed) {
1535 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001536 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001537 getContext()->fadePointer();
1538 }
1539
1540 if (mParameters.wake) {
1541 policyFlags |= POLICY_FLAG_WAKE;
1542 }
1543 }
1544
1545 // Consume raw off-screen touches before cooking pointer data.
1546 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001547 bool consumed;
1548 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1549 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001550 mCurrentRawState.rawPointerData.clear();
1551 }
1552
1553 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1554 // with cooked pointer data that has the same ids and indices as the raw data.
1555 // The following code can use either the raw or cooked data, as needed.
1556 cookPointerData();
1557
1558 // Apply stylus pressure to current cooked state.
1559 applyExternalStylusTouchState(when);
1560
1561 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001562 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1563 mSource, mViewport.displayId, policyFlags,
1564 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001565
1566 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001567 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001568 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1569 uint32_t id = idBits.clearFirstMarkedBit();
1570 const RawPointerData::Pointer& pointer =
1571 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001572 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001573 mCurrentCookedState.stylusIdBits.markBit(id);
1574 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1575 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1576 mCurrentCookedState.fingerIdBits.markBit(id);
1577 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1578 mCurrentCookedState.mouseIdBits.markBit(id);
1579 }
1580 }
1581 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1582 uint32_t id = idBits.clearFirstMarkedBit();
1583 const RawPointerData::Pointer& pointer =
1584 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001585 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001586 mCurrentCookedState.stylusIdBits.markBit(id);
1587 }
1588 }
1589
1590 // Stylus takes precedence over all tools, then mouse, then finger.
1591 PointerUsage pointerUsage = mPointerUsage;
1592 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1593 mCurrentCookedState.mouseIdBits.clear();
1594 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001595 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001596 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1597 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001598 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001599 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1600 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001601 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001602 }
1603
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001604 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001605 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001606 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001607 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001608 out += dispatchButtonRelease(when, readTime, policyFlags);
1609 out += dispatchHoverExit(when, readTime, policyFlags);
1610 out += dispatchTouches(when, readTime, policyFlags);
1611 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1612 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001613 }
1614
1615 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1616 mCurrentMotionAborted = false;
1617 }
1618 }
1619
1620 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001621 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1622 mSource, mViewport.displayId, policyFlags,
1623 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001624
1625 // Clear some transient state.
1626 mCurrentRawState.rawVScroll = 0;
1627 mCurrentRawState.rawHScroll = 0;
1628
1629 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001630 mLastRawState = mCurrentRawState;
1631 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001632 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001633}
1634
Garfield Tanc734e4f2021-01-15 20:01:39 -08001635void TouchInputMapper::updateTouchSpots() {
1636 if (!mConfig.showTouches || mPointerController == nullptr) {
1637 return;
1638 }
1639
1640 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1641 // clear touch spots.
1642 if (mDeviceMode != DeviceMode::DIRECT &&
1643 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1644 return;
1645 }
1646
1647 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1648 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1649
1650 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001651 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1652 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001653 mCurrentCookedState.cookedPointerData.touchingIdBits,
1654 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001655}
1656
1657bool TouchInputMapper::isTouchScreen() {
1658 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1659 mParameters.hasAssociatedDisplay;
1660}
1661
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001662void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001663 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1664 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001665 const int32_t pressedButtons =
1666 filterButtonState(mConfig,
1667 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001668 const int32_t releasedButtons =
1669 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1670
1671 mCurrentRawState.buttonState |= pressedButtons;
1672 mCurrentRawState.buttonState &= ~releasedButtons;
1673
1674 mExternalStylusButtonsApplied |= pressedButtons;
1675 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001676 }
1677}
1678
1679void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1680 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1681 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001682 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1683 return;
1684 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001685
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001686 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1687 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1688 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1689 : 0.f;
1690 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1691 pressure = *mExternalStylusState.pressure;
1692 }
1693 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1694 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001695
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001696 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001697 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001698 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001699 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001700 }
1701}
1702
1703bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001704 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001705 return false;
1706 }
1707
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001708 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001709 if (mFusedStylusPointerId &&
1710 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001711 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001712 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001713 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001714 }
1715
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001716 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1717 state.rawPointerData.pointerCount != 0;
1718 if (!initialDown) {
1719 return false;
1720 }
1721
1722 if (!mExternalStylusState.pressure) {
1723 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1724 return false;
1725 }
1726
1727 if (*mExternalStylusState.pressure != 0.0f) {
1728 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1729 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1730 return false;
1731 }
1732
1733 if (timeout) {
1734 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1735 mFusedStylusPointerId.reset();
1736 mExternalStylusFusionTimeout = LLONG_MAX;
1737 return false;
1738 }
1739
1740 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1741 // being processed until we either get pressure data or timeout.
1742 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1743 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1744 }
1745 ALOGD_IF(DEBUG_STYLUS_FUSION,
1746 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1747 mExternalStylusFusionTimeout);
1748 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1749 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001750}
1751
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001752std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1753 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001754 if (mDeviceMode == DeviceMode::POINTER) {
1755 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001756 // Since this is a synthetic event, we can consider its latency to be zero
1757 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001758 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001759 }
Michael Wright227c5542020-07-02 18:30:52 +01001760 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001761 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001762 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001763 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1764 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1765 }
1766 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001767 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001768}
1769
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001770std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1771 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001772 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001773 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001774 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001775 // The following three cases are handled here:
1776 // - We're in the middle of a fused stream of data;
1777 // - We're waiting on external stylus data before dispatching the initial down; or
1778 // - Only the button state, which is not reported through a specific pointer, has changed.
1779 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001780 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001781 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001782 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001783 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001784}
1785
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001786std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1787 uint32_t policyFlags, bool& outConsumed) {
1788 outConsumed = false;
1789 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001790 // Check for release of a virtual key.
1791 if (mCurrentVirtualKey.down) {
1792 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1793 // Pointer went up while virtual key was down.
1794 mCurrentVirtualKey.down = false;
1795 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001796 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1797 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1798 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001799 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1800 AKEY_EVENT_FLAG_FROM_SYSTEM |
1801 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001802 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001803 outConsumed = true;
1804 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001805 }
1806
1807 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1808 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1809 const RawPointerData::Pointer& pointer =
1810 mCurrentRawState.rawPointerData.pointerForId(id);
1811 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1812 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1813 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001814 outConsumed = true;
1815 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001816 }
1817 }
1818
1819 // Pointer left virtual key area or another pointer also went down.
1820 // Send key cancellation but do not consume the touch yet.
1821 // This is useful when the user swipes through from the virtual key area
1822 // into the main display surface.
1823 mCurrentVirtualKey.down = false;
1824 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001825 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1826 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001827 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1828 AKEY_EVENT_FLAG_FROM_SYSTEM |
1829 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1830 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001831 }
1832 }
1833
1834 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1835 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1836 // Pointer just went down. Check for virtual key press or off-screen touches.
1837 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1838 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001839 // Skip checking whether the pointer is inside the physical frame if the device is in
1840 // unscaled mode.
1841 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1842 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001843 // If exactly one pointer went down, check for virtual key hit.
1844 // Otherwise we will drop the entire stroke.
1845 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1846 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1847 if (virtualKey) {
1848 mCurrentVirtualKey.down = true;
1849 mCurrentVirtualKey.downTime = when;
1850 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1851 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1852 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001853 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1854 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001855
1856 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001857 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1858 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1859 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001860 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1861 AKEY_EVENT_ACTION_DOWN,
1862 AKEY_EVENT_FLAG_FROM_SYSTEM |
1863 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001864 }
1865 }
1866 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001867 outConsumed = true;
1868 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001869 }
1870 }
1871
1872 // Disable all virtual key touches that happen within a short time interval of the
1873 // most recent touch within the screen area. The idea is to filter out stray
1874 // virtual key presses when interacting with the touch screen.
1875 //
1876 // Problems we're trying to solve:
1877 //
1878 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1879 // virtual key area that is implemented by a separate touch panel and accidentally
1880 // triggers a virtual key.
1881 //
1882 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1883 // area and accidentally triggers a virtual key. This often happens when virtual keys
1884 // are layed out below the screen near to where the on screen keyboard's space bar
1885 // is displayed.
1886 if (mConfig.virtualKeyQuietTime > 0 &&
1887 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001888 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001889 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001890 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001891}
1892
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001893NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1894 uint32_t policyFlags, int32_t keyEventAction,
1895 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001896 int32_t keyCode = mCurrentVirtualKey.keyCode;
1897 int32_t scanCode = mCurrentVirtualKey.scanCode;
1898 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001899 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001900 policyFlags |= POLICY_FLAG_VIRTUAL;
1901
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001902 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1903 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1904 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001905}
1906
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001907std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1908 uint32_t policyFlags) {
1909 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001910 if (mCurrentMotionAborted) {
1911 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001912 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001913 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001914 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1915 if (!currentIdBits.isEmpty()) {
1916 int32_t metaState = getContext()->getGlobalMetaState();
1917 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001918 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001919 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1920 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001921 mCurrentCookedState.cookedPointerData.pointerProperties,
1922 mCurrentCookedState.cookedPointerData.pointerCoords,
1923 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1924 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1925 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001926 mCurrentMotionAborted = true;
1927 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001928 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001929}
1930
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001931// Updates pointer coords and properties for pointers with specified ids that have moved.
1932// Returns true if any of them changed.
1933static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1934 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1935 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1936 BitSet32 idBits) {
1937 bool changed = false;
1938 while (!idBits.isEmpty()) {
1939 uint32_t id = idBits.clearFirstMarkedBit();
1940 uint32_t inIndex = inIdToIndex[id];
1941 uint32_t outIndex = outIdToIndex[id];
1942
1943 const PointerProperties& curInProperties = inProperties[inIndex];
1944 const PointerCoords& curInCoords = inCoords[inIndex];
1945 PointerProperties& curOutProperties = outProperties[outIndex];
1946 PointerCoords& curOutCoords = outCoords[outIndex];
1947
1948 if (curInProperties != curOutProperties) {
1949 curOutProperties.copyFrom(curInProperties);
1950 changed = true;
1951 }
1952
1953 if (curInCoords != curOutCoords) {
1954 curOutCoords.copyFrom(curInCoords);
1955 changed = true;
1956 }
1957 }
1958 return changed;
1959}
1960
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001961std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1962 uint32_t policyFlags) {
1963 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001964 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1965 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1966 int32_t metaState = getContext()->getGlobalMetaState();
1967 int32_t buttonState = mCurrentCookedState.buttonState;
1968
1969 if (currentIdBits == lastIdBits) {
1970 if (!currentIdBits.isEmpty()) {
1971 // No pointer id changes so this is a move event.
1972 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001973 out.push_back(
1974 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1975 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1976 mCurrentCookedState.cookedPointerData.pointerProperties,
1977 mCurrentCookedState.cookedPointerData.pointerCoords,
1978 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1979 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1980 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001981 }
1982 } else {
1983 // There may be pointers going up and pointers going down and pointers moving
1984 // all at the same time.
1985 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1986 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1987 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1988 BitSet32 dispatchedIdBits(lastIdBits.value);
1989
1990 // Update last coordinates of pointers that have moved so that we observe the new
1991 // pointer positions at the same time as other pointers that have just gone up.
1992 bool moveNeeded =
1993 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1994 mCurrentCookedState.cookedPointerData.pointerCoords,
1995 mCurrentCookedState.cookedPointerData.idToIndex,
1996 mLastCookedState.cookedPointerData.pointerProperties,
1997 mLastCookedState.cookedPointerData.pointerCoords,
1998 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1999 if (buttonState != mLastCookedState.buttonState) {
2000 moveNeeded = true;
2001 }
2002
2003 // Dispatch pointer up events.
2004 while (!upIdBits.isEmpty()) {
2005 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002006 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002007 if (isCanceled) {
2008 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2009 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002010 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2011 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2012 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2013 buttonState, 0,
2014 mLastCookedState.cookedPointerData.pointerProperties,
2015 mLastCookedState.cookedPointerData.pointerCoords,
2016 mLastCookedState.cookedPointerData.idToIndex,
2017 dispatchedIdBits, upId, mOrientedXPrecision,
2018 mOrientedYPrecision, mDownTime,
2019 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002020 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002021 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002022 }
2023
2024 // Dispatch move events if any of the remaining pointers moved from their old locations.
2025 // Although applications receive new locations as part of individual pointer up
2026 // events, they do not generally handle them except when presented in a move event.
2027 if (moveNeeded && !moveIdBits.isEmpty()) {
2028 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002029 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2030 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2031 mCurrentCookedState.cookedPointerData.pointerProperties,
2032 mCurrentCookedState.cookedPointerData.pointerCoords,
2033 mCurrentCookedState.cookedPointerData.idToIndex,
2034 dispatchedIdBits, -1, mOrientedXPrecision,
2035 mOrientedYPrecision, mDownTime,
2036 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002037 }
2038
2039 // Dispatch pointer down events using the new pointer locations.
2040 while (!downIdBits.isEmpty()) {
2041 uint32_t downId = downIdBits.clearFirstMarkedBit();
2042 dispatchedIdBits.markBit(downId);
2043
2044 if (dispatchedIdBits.count() == 1) {
2045 // First pointer is going down. Set down time.
2046 mDownTime = when;
2047 }
2048
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002049 out.push_back(
2050 dispatchMotion(when, readTime, policyFlags, mSource,
2051 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2052 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2053 mCurrentCookedState.cookedPointerData.pointerCoords,
2054 mCurrentCookedState.cookedPointerData.idToIndex,
2055 dispatchedIdBits, downId, mOrientedXPrecision,
2056 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002057 }
2058 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002059 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002060}
2061
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002062std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2063 uint32_t policyFlags) {
2064 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002065 if (mSentHoverEnter &&
2066 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2067 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2068 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002069 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2070 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2071 mLastCookedState.buttonState, 0,
2072 mLastCookedState.cookedPointerData.pointerProperties,
2073 mLastCookedState.cookedPointerData.pointerCoords,
2074 mLastCookedState.cookedPointerData.idToIndex,
2075 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2076 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2077 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002078 mSentHoverEnter = false;
2079 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002080 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002081}
2082
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002083std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2084 uint32_t policyFlags) {
2085 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002086 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2087 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2088 int32_t metaState = getContext()->getGlobalMetaState();
2089 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002090 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2091 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2092 mCurrentRawState.buttonState, 0,
2093 mCurrentCookedState.cookedPointerData.pointerProperties,
2094 mCurrentCookedState.cookedPointerData.pointerCoords,
2095 mCurrentCookedState.cookedPointerData.idToIndex,
2096 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2097 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2098 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002099 mSentHoverEnter = true;
2100 }
2101
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002102 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2103 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2104 mCurrentRawState.buttonState, 0,
2105 mCurrentCookedState.cookedPointerData.pointerProperties,
2106 mCurrentCookedState.cookedPointerData.pointerCoords,
2107 mCurrentCookedState.cookedPointerData.idToIndex,
2108 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2109 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2110 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002111 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002112 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002113}
2114
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002115std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2116 uint32_t policyFlags) {
2117 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002118 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2119 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2120 const int32_t metaState = getContext()->getGlobalMetaState();
2121 int32_t buttonState = mLastCookedState.buttonState;
2122 while (!releasedButtons.isEmpty()) {
2123 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2124 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002125 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2126 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2127 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002128 mLastCookedState.cookedPointerData.pointerProperties,
2129 mLastCookedState.cookedPointerData.pointerCoords,
2130 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002131 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2132 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002133 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002134 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002135}
2136
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002137std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2138 uint32_t policyFlags) {
2139 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002140 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2141 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2142 const int32_t metaState = getContext()->getGlobalMetaState();
2143 int32_t buttonState = mLastCookedState.buttonState;
2144 while (!pressedButtons.isEmpty()) {
2145 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2146 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002147 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2148 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2149 buttonState, 0,
2150 mCurrentCookedState.cookedPointerData.pointerProperties,
2151 mCurrentCookedState.cookedPointerData.pointerCoords,
2152 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2153 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2154 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002155 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002156 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002157}
2158
2159const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2160 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2161 return cookedPointerData.touchingIdBits;
2162 }
2163 return cookedPointerData.hoveringIdBits;
2164}
2165
2166void TouchInputMapper::cookPointerData() {
2167 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2168
2169 mCurrentCookedState.cookedPointerData.clear();
2170 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2171 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2172 mCurrentRawState.rawPointerData.hoveringIdBits;
2173 mCurrentCookedState.cookedPointerData.touchingIdBits =
2174 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002175 mCurrentCookedState.cookedPointerData.canceledIdBits =
2176 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002177
2178 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2179 mCurrentCookedState.buttonState = 0;
2180 } else {
2181 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2182 }
2183
2184 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002185 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002186 for (uint32_t i = 0; i < currentPointerCount; i++) {
2187 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2188
2189 // Size
2190 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2191 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002192 case Calibration::SizeCalibration::GEOMETRIC:
2193 case Calibration::SizeCalibration::DIAMETER:
2194 case Calibration::SizeCalibration::BOX:
2195 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002196 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2197 touchMajor = in.touchMajor;
2198 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2199 toolMajor = in.toolMajor;
2200 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2201 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2202 : in.touchMajor;
2203 } else if (mRawPointerAxes.touchMajor.valid) {
2204 toolMajor = touchMajor = in.touchMajor;
2205 toolMinor = touchMinor =
2206 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2207 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2208 : in.touchMajor;
2209 } else if (mRawPointerAxes.toolMajor.valid) {
2210 touchMajor = toolMajor = in.toolMajor;
2211 touchMinor = toolMinor =
2212 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2213 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2214 : in.toolMajor;
2215 } else {
2216 ALOG_ASSERT(false,
2217 "No touch or tool axes. "
2218 "Size calibration should have been resolved to NONE.");
2219 touchMajor = 0;
2220 touchMinor = 0;
2221 toolMajor = 0;
2222 toolMinor = 0;
2223 size = 0;
2224 }
2225
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002226 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002227 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2228 if (touchingCount > 1) {
2229 touchMajor /= touchingCount;
2230 touchMinor /= touchingCount;
2231 toolMajor /= touchingCount;
2232 toolMinor /= touchingCount;
2233 size /= touchingCount;
2234 }
2235 }
2236
Michael Wright227c5542020-07-02 18:30:52 +01002237 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002238 touchMajor *= mGeometricScale;
2239 touchMinor *= mGeometricScale;
2240 toolMajor *= mGeometricScale;
2241 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002242 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002243 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2244 touchMinor = touchMajor;
2245 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2246 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002247 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002248 touchMinor = touchMajor;
2249 toolMinor = toolMajor;
2250 }
2251
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002252 mCalibration.applySizeScaleAndBias(touchMajor);
2253 mCalibration.applySizeScaleAndBias(touchMinor);
2254 mCalibration.applySizeScaleAndBias(toolMajor);
2255 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002256 size *= mSizeScale;
2257 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002258 case Calibration::SizeCalibration::DEFAULT:
2259 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2260 break;
2261 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002262 touchMajor = 0;
2263 touchMinor = 0;
2264 toolMajor = 0;
2265 toolMinor = 0;
2266 size = 0;
2267 break;
2268 }
2269
2270 // Pressure
2271 float pressure;
2272 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002273 case Calibration::PressureCalibration::PHYSICAL:
2274 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002275 pressure = in.pressure * mPressureScale;
2276 break;
2277 default:
2278 pressure = in.isHovering ? 0 : 1;
2279 break;
2280 }
2281
2282 // Tilt and Orientation
2283 float tilt;
2284 float orientation;
2285 if (mHaveTilt) {
2286 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2287 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002288 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002289 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2290 } else {
2291 tilt = 0;
2292
2293 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002294 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002295 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002296 break;
Michael Wright227c5542020-07-02 18:30:52 +01002297 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002298 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2299 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2300 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002301 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002302 float confidence = hypotf(c1, c2);
2303 float scale = 1.0f + confidence / 16.0f;
2304 touchMajor *= scale;
2305 touchMinor /= scale;
2306 toolMajor *= scale;
2307 toolMinor /= scale;
2308 } else {
2309 orientation = 0;
2310 }
2311 break;
2312 }
2313 default:
2314 orientation = 0;
2315 }
2316 }
2317
2318 // Distance
2319 float distance;
2320 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002321 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002322 distance = in.distance * mDistanceScale;
2323 break;
2324 default:
2325 distance = 0;
2326 }
2327
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002328 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2329 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002330 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2331 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002332
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002333 // Write output coords.
2334 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2335 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002336 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2337 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002338 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2339 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2340 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2341 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2342 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2343 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2344 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002345 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2346 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002347
Chris Ye364fdb52020-08-05 15:07:56 -07002348 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002349 uint32_t id = in.id;
2350 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2351 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2352 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002353 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2354 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002355 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2356 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2357 }
2358
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002359 // Write output properties.
2360 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002361 properties.clear();
2362 properties.id = id;
2363 properties.toolType = in.toolType;
2364
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002365 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002366 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002367 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002368 }
2369}
2370
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002371std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2372 uint32_t policyFlags,
2373 PointerUsage pointerUsage) {
2374 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002375 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002376 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002377 mPointerUsage = pointerUsage;
2378 }
2379
2380 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002381 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002382 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002383 break;
Michael Wright227c5542020-07-02 18:30:52 +01002384 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002385 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002386 break;
Michael Wright227c5542020-07-02 18:30:52 +01002387 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002388 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002389 break;
Michael Wright227c5542020-07-02 18:30:52 +01002390 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391 break;
2392 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002393 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002394}
2395
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002396std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2397 uint32_t policyFlags) {
2398 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002399 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002400 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002401 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002402 break;
Michael Wright227c5542020-07-02 18:30:52 +01002403 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002404 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002405 break;
Michael Wright227c5542020-07-02 18:30:52 +01002406 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002407 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002408 break;
Michael Wright227c5542020-07-02 18:30:52 +01002409 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002410 break;
2411 }
2412
Michael Wright227c5542020-07-02 18:30:52 +01002413 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002414 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002415}
2416
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002417std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2418 uint32_t policyFlags,
2419 bool isTimeout) {
2420 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002421 // Update current gesture coordinates.
2422 bool cancelPreviousGesture, finishPreviousGesture;
2423 bool sendEvents =
2424 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2425 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002426 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002427 }
2428 if (finishPreviousGesture) {
2429 cancelPreviousGesture = false;
2430 }
2431
2432 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002433 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002434 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002435 if (finishPreviousGesture || cancelPreviousGesture) {
2436 mPointerController->clearSpots();
2437 }
2438
Michael Wright227c5542020-07-02 18:30:52 +01002439 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002440 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2441 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002442 mPointerGesture.currentGestureIdBits,
2443 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002444 }
2445 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002446 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002447 }
2448
2449 // Show or hide the pointer if needed.
2450 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002451 case PointerGesture::Mode::NEUTRAL:
2452 case PointerGesture::Mode::QUIET:
2453 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2454 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002455 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002456 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002457 }
2458 break;
Michael Wright227c5542020-07-02 18:30:52 +01002459 case PointerGesture::Mode::TAP:
2460 case PointerGesture::Mode::TAP_DRAG:
2461 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2462 case PointerGesture::Mode::HOVER:
2463 case PointerGesture::Mode::PRESS:
2464 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002465 // Unfade the pointer when the current gesture manipulates the
2466 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002467 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002468 break;
Michael Wright227c5542020-07-02 18:30:52 +01002469 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002470 // Fade the pointer when the current gesture manipulates a different
2471 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002472 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002473 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002474 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002475 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002476 }
2477 break;
2478 }
2479
2480 // Send events!
2481 int32_t metaState = getContext()->getGlobalMetaState();
2482 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002483 const MotionClassification classification =
2484 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2485 ? MotionClassification::TWO_FINGER_SWIPE
2486 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002487
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002488 uint32_t flags = 0;
2489
2490 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2491 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2492 }
2493
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002494 // Update last coordinates of pointers that have moved so that we observe the new
2495 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002496 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2497 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2498 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2499 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2500 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2501 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002502 bool moveNeeded = false;
2503 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2504 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2505 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2506 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2507 mPointerGesture.lastGestureIdBits.value);
2508 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2509 mPointerGesture.currentGestureCoords,
2510 mPointerGesture.currentGestureIdToIndex,
2511 mPointerGesture.lastGestureProperties,
2512 mPointerGesture.lastGestureCoords,
2513 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2514 if (buttonState != mLastCookedState.buttonState) {
2515 moveNeeded = true;
2516 }
2517 }
2518
2519 // Send motion events for all pointers that went up or were canceled.
2520 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2521 if (!dispatchedGestureIdBits.isEmpty()) {
2522 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002523 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002524 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002525 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002526 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2527 mPointerGesture.lastGestureProperties,
2528 mPointerGesture.lastGestureCoords,
2529 mPointerGesture.lastGestureIdToIndex,
2530 dispatchedGestureIdBits, -1, 0, 0,
2531 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002532
2533 dispatchedGestureIdBits.clear();
2534 } else {
2535 BitSet32 upGestureIdBits;
2536 if (finishPreviousGesture) {
2537 upGestureIdBits = dispatchedGestureIdBits;
2538 } else {
2539 upGestureIdBits.value =
2540 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2541 }
2542 while (!upGestureIdBits.isEmpty()) {
2543 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2544
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002545 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2546 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2547 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2548 mPointerGesture.lastGestureProperties,
2549 mPointerGesture.lastGestureCoords,
2550 mPointerGesture.lastGestureIdToIndex,
2551 dispatchedGestureIdBits, id, 0, 0,
2552 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002553
2554 dispatchedGestureIdBits.clearBit(id);
2555 }
2556 }
2557 }
2558
2559 // Send motion events for all pointers that moved.
2560 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002561 out.push_back(
2562 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2563 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2564 mPointerGesture.currentGestureProperties,
2565 mPointerGesture.currentGestureCoords,
2566 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2567 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002568 }
2569
2570 // Send motion events for all pointers that went down.
2571 if (down) {
2572 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2573 ~dispatchedGestureIdBits.value);
2574 while (!downGestureIdBits.isEmpty()) {
2575 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2576 dispatchedGestureIdBits.markBit(id);
2577
2578 if (dispatchedGestureIdBits.count() == 1) {
2579 mPointerGesture.downTime = when;
2580 }
2581
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002582 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2583 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2584 buttonState, 0, mPointerGesture.currentGestureProperties,
2585 mPointerGesture.currentGestureCoords,
2586 mPointerGesture.currentGestureIdToIndex,
2587 dispatchedGestureIdBits, id, 0, 0,
2588 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002589 }
2590 }
2591
2592 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002593 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002594 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2595 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2596 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2597 mPointerGesture.currentGestureProperties,
2598 mPointerGesture.currentGestureCoords,
2599 mPointerGesture.currentGestureIdToIndex,
2600 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2601 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002602 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2603 // Synthesize a hover move event after all pointers go up to indicate that
2604 // the pointer is hovering again even if the user is not currently touching
2605 // the touch pad. This ensures that a view will receive a fresh hover enter
2606 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002607 float x, y;
2608 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002609
2610 PointerProperties pointerProperties;
2611 pointerProperties.clear();
2612 pointerProperties.id = 0;
2613 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2614
2615 PointerCoords pointerCoords;
2616 pointerCoords.clear();
2617 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2618 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2619
2620 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002621 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2622 mSource, displayId, policyFlags,
2623 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2624 buttonState, MotionClassification::NONE,
2625 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2626 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2627 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002628 }
2629
2630 // Update state.
2631 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2632 if (!down) {
2633 mPointerGesture.lastGestureIdBits.clear();
2634 } else {
2635 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2636 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2637 uint32_t id = idBits.clearFirstMarkedBit();
2638 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2639 mPointerGesture.lastGestureProperties[index].copyFrom(
2640 mPointerGesture.currentGestureProperties[index]);
2641 mPointerGesture.lastGestureCoords[index].copyFrom(
2642 mPointerGesture.currentGestureCoords[index]);
2643 mPointerGesture.lastGestureIdToIndex[id] = index;
2644 }
2645 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002646 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002647}
2648
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002649std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2650 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002651 const MotionClassification classification =
2652 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2653 ? MotionClassification::TWO_FINGER_SWIPE
2654 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002655 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002656 // Cancel previously dispatches pointers.
2657 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2658 int32_t metaState = getContext()->getGlobalMetaState();
2659 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002660 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002661 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2662 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002663 mPointerGesture.lastGestureProperties,
2664 mPointerGesture.lastGestureCoords,
2665 mPointerGesture.lastGestureIdToIndex,
2666 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2667 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002668 }
2669
2670 // Reset the current pointer gesture.
2671 mPointerGesture.reset();
2672 mPointerVelocityControl.reset();
2673
2674 // Remove any current spots.
2675 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002676 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002677 mPointerController->clearSpots();
2678 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002679 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002680}
2681
2682bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2683 bool* outFinishPreviousGesture, bool isTimeout) {
2684 *outCancelPreviousGesture = false;
2685 *outFinishPreviousGesture = false;
2686
2687 // Handle TAP timeout.
2688 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002689 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002690
Michael Wright227c5542020-07-02 18:30:52 +01002691 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002692 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2693 // The tap/drag timeout has not yet expired.
2694 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2695 mConfig.pointerGestureTapDragInterval);
2696 } else {
2697 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002698 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002699 *outFinishPreviousGesture = true;
2700
2701 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002702 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002703 mPointerGesture.currentGestureIdBits.clear();
2704
2705 mPointerVelocityControl.reset();
2706 return true;
2707 }
2708 }
2709
2710 // We did not handle this timeout.
2711 return false;
2712 }
2713
2714 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2715 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2716
2717 // Update the velocity tracker.
2718 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002719 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002720 uint32_t id = idBits.clearFirstMarkedBit();
2721 const RawPointerData::Pointer& pointer =
2722 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002723 const float x = pointer.x * mPointerXMovementScale;
2724 const float y = pointer.y * mPointerYMovementScale;
2725 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2726 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002727 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002728 }
2729
2730 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2731 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002732 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2733 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2734 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002735 mPointerGesture.resetTap();
2736 }
2737
2738 // Pick a new active touch id if needed.
2739 // Choose an arbitrary pointer that just went down, if there is one.
2740 // Otherwise choose an arbitrary remaining pointer.
2741 // This guarantees we always have an active touch id when there is at least one pointer.
2742 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002743 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002744 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002745 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002746 mPointerGesture.firstTouchTime = when;
2747 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002748 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2749 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2750 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2751 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002752 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002753 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002754
2755 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002756 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002757 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002758 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2759 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2760 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002761 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002762 *outFinishPreviousGesture = true;
2763 }
2764
2765 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002766 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002767 mPointerGesture.currentGestureIdBits.clear();
2768
2769 mPointerVelocityControl.reset();
2770 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2771 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2772 // The pointer follows the active touch point.
2773 // Emit DOWN, MOVE, UP events at the pointer location.
2774 //
2775 // Only the active touch matters; other fingers are ignored. This policy helps
2776 // to handle the case where the user places a second finger on the touch pad
2777 // to apply the necessary force to depress an integrated button below the surface.
2778 // We don't want the second finger to be delivered to applications.
2779 //
2780 // For this to work well, we need to make sure to track the pointer that is really
2781 // active. If the user first puts one finger down to click then adds another
2782 // finger to drag then the active pointer should switch to the finger that is
2783 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002784 ALOGD_IF(DEBUG_GESTURES,
2785 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2786 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002787 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002788 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002789 *outFinishPreviousGesture = true;
2790 mPointerGesture.activeGestureId = 0;
2791 }
2792
2793 // Switch pointers if needed.
2794 // Find the fastest pointer and follow it.
2795 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002796 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002797 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002798 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002799 ALOGD_IF(DEBUG_GESTURES,
2800 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2801 "bestSpeed=%0.3f",
2802 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002803 }
2804 }
2805
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002806 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002807 // When using spots, the click will occur at the position of the anchor
2808 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002809 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002810 } else {
2811 mPointerVelocityControl.reset();
2812 }
2813
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002814 float x, y;
2815 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002816
Michael Wright227c5542020-07-02 18:30:52 +01002817 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002818 mPointerGesture.currentGestureIdBits.clear();
2819 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2820 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2821 mPointerGesture.currentGestureProperties[0].clear();
2822 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2823 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2824 mPointerGesture.currentGestureCoords[0].clear();
2825 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2826 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2827 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2828 } else if (currentFingerCount == 0) {
2829 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002830 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002831 *outFinishPreviousGesture = true;
2832 }
2833
2834 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2835 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2836 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002837 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2838 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002839 lastFingerCount == 1) {
2840 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002841 float x, y;
2842 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002843 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2844 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002845 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002846
2847 mPointerGesture.tapUpTime = when;
2848 getContext()->requestTimeoutAtTime(when +
2849 mConfig.pointerGestureTapDragInterval);
2850
2851 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002852 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002853 mPointerGesture.currentGestureIdBits.clear();
2854 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2855 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2856 mPointerGesture.currentGestureProperties[0].clear();
2857 mPointerGesture.currentGestureProperties[0].id =
2858 mPointerGesture.activeGestureId;
2859 mPointerGesture.currentGestureProperties[0].toolType =
2860 AMOTION_EVENT_TOOL_TYPE_FINGER;
2861 mPointerGesture.currentGestureCoords[0].clear();
2862 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2863 mPointerGesture.tapX);
2864 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2865 mPointerGesture.tapY);
2866 mPointerGesture.currentGestureCoords[0]
2867 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2868
2869 tapped = true;
2870 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002871 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2872 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002873 }
2874 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002875 if (DEBUG_GESTURES) {
2876 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2877 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2878 (when - mPointerGesture.tapDownTime) * 0.000001f);
2879 } else {
2880 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2881 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002882 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002883 }
2884 }
2885
2886 mPointerVelocityControl.reset();
2887
2888 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002889 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002890 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002891 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002892 mPointerGesture.currentGestureIdBits.clear();
2893 }
2894 } else if (currentFingerCount == 1) {
2895 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2896 // The pointer follows the active touch point.
2897 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2898 // When in TAP_DRAG, emit MOVE events at the pointer location.
2899 ALOG_ASSERT(activeTouchId >= 0);
2900
Michael Wright227c5542020-07-02 18:30:52 +01002901 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2902 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002903 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002904 float x, y;
2905 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002906 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2907 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002908 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002909 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002910 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2911 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002912 }
2913 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002914 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2915 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002916 }
Michael Wright227c5542020-07-02 18:30:52 +01002917 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2918 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002919 }
2920
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002921 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002922 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002923 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002924 } else {
2925 mPointerVelocityControl.reset();
2926 }
2927
2928 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002929 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00002930 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002931 down = true;
2932 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002933 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01002934 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002935 *outFinishPreviousGesture = true;
2936 }
2937 mPointerGesture.activeGestureId = 0;
2938 down = false;
2939 }
2940
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002941 float x, y;
2942 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002943
2944 mPointerGesture.currentGestureIdBits.clear();
2945 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2946 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2947 mPointerGesture.currentGestureProperties[0].clear();
2948 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2949 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2950 mPointerGesture.currentGestureCoords[0].clear();
2951 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2952 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2953 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2954 down ? 1.0f : 0.0f);
2955
2956 if (lastFingerCount == 0 && currentFingerCount != 0) {
2957 mPointerGesture.resetTap();
2958 mPointerGesture.tapDownTime = when;
2959 mPointerGesture.tapX = x;
2960 mPointerGesture.tapY = y;
2961 }
2962 } else {
2963 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002964 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002965 }
2966
2967 mPointerController->setButtonState(mCurrentRawState.buttonState);
2968
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002969 if (DEBUG_GESTURES) {
2970 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
2971 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
2972 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
2973 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
2974 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
2975 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
2976 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
2977 uint32_t id = idBits.clearFirstMarkedBit();
2978 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2979 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
2980 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
2981 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
2982 "x=%0.3f, y=%0.3f, pressure=%0.3f",
2983 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
2984 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
2985 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
2986 }
2987 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
2988 uint32_t id = idBits.clearFirstMarkedBit();
2989 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
2990 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
2991 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
2992 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
2993 "x=%0.3f, y=%0.3f, pressure=%0.3f",
2994 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
2995 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
2996 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
2997 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002998 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002999 return true;
3000}
3001
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003002bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3003 if (mPointerGesture.activeTouchId < 0) {
3004 mPointerGesture.resetQuietTime();
3005 return false;
3006 }
3007
3008 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3009 return true;
3010 }
3011
3012 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3013 bool isQuietTime = false;
3014 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3015 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3016 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3017 currentFingerCount < 2) {
3018 // Enter quiet time when exiting swipe or freeform state.
3019 // This is to prevent accidentally entering the hover state and flinging the
3020 // pointer when finishing a swipe and there is still one pointer left onscreen.
3021 isQuietTime = true;
3022 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3023 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3024 // Enter quiet time when releasing the button and there are still two or more
3025 // fingers down. This may indicate that one finger was used to press the button
3026 // but it has not gone up yet.
3027 isQuietTime = true;
3028 }
3029 if (isQuietTime) {
3030 mPointerGesture.quietTime = when;
3031 }
3032 return isQuietTime;
3033}
3034
3035std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3036 int32_t bestId = -1;
3037 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3038 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3039 uint32_t id = idBits.clearFirstMarkedBit();
3040 std::optional<float> vx =
3041 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3042 std::optional<float> vy =
3043 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3044 if (vx && vy) {
3045 float speed = hypotf(*vx, *vy);
3046 if (speed > bestSpeed) {
3047 bestId = id;
3048 bestSpeed = speed;
3049 }
3050 }
3051 }
3052 return std::make_pair(bestId, bestSpeed);
3053}
3054
3055void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3056 bool* finishPreviousGesture) {
3057 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3058 // to move before deciding what to do.
3059 //
3060 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3061 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3062 // just a press or long-press at the pointer location.
3063 //
3064 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3065 // pointer location.
3066 //
3067 // When the two fingers move enough or when additional fingers are added, we make a decision to
3068 // transition into SWIPE or FREEFORM mode accordingly.
3069 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3070 ALOG_ASSERT(activeTouchId >= 0);
3071
3072 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3073 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3074 bool settled =
3075 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3076 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3077 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3078 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3079 *finishPreviousGesture = true;
3080 } else if (!settled && currentFingerCount > lastFingerCount) {
3081 // Additional pointers have gone down but not yet settled.
3082 // Reset the gesture.
3083 ALOGD_IF(DEBUG_GESTURES,
3084 "Gestures: Resetting gesture since additional pointers went down for "
3085 "MULTITOUCH, settle time remaining %0.3fms",
3086 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3087 when) * 0.000001f);
3088 *cancelPreviousGesture = true;
3089 } else {
3090 // Continue previous gesture.
3091 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3092 }
3093
3094 if (*finishPreviousGesture || *cancelPreviousGesture) {
3095 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3096 mPointerGesture.activeGestureId = 0;
3097 mPointerGesture.referenceIdBits.clear();
3098 mPointerVelocityControl.reset();
3099
3100 // Use the centroid and pointer location as the reference points for the gesture.
3101 ALOGD_IF(DEBUG_GESTURES,
3102 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3103 "%0.3fms",
3104 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3105 when) * 0.000001f);
3106 mCurrentRawState.rawPointerData
3107 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3108 &mPointerGesture.referenceTouchY);
3109 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3110 &mPointerGesture.referenceGestureY);
3111 }
3112
3113 // Clear the reference deltas for fingers not yet included in the reference calculation.
3114 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3115 ~mPointerGesture.referenceIdBits.value);
3116 !idBits.isEmpty();) {
3117 uint32_t id = idBits.clearFirstMarkedBit();
3118 mPointerGesture.referenceDeltas[id].dx = 0;
3119 mPointerGesture.referenceDeltas[id].dy = 0;
3120 }
3121 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3122
3123 // Add delta for all fingers and calculate a common movement delta.
3124 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3125 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3126 mCurrentCookedState.fingerIdBits.value);
3127 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3128 bool first = (idBits == commonIdBits);
3129 uint32_t id = idBits.clearFirstMarkedBit();
3130 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3131 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3132 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3133 delta.dx += cpd.x - lpd.x;
3134 delta.dy += cpd.y - lpd.y;
3135
3136 if (first) {
3137 commonDeltaRawX = delta.dx;
3138 commonDeltaRawY = delta.dy;
3139 } else {
3140 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3141 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3142 }
3143 }
3144
3145 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3146 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3147 float dist[MAX_POINTER_ID + 1];
3148 int32_t distOverThreshold = 0;
3149 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3150 uint32_t id = idBits.clearFirstMarkedBit();
3151 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3152 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3153 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3154 distOverThreshold += 1;
3155 }
3156 }
3157
3158 // Only transition when at least two pointers have moved further than
3159 // the minimum distance threshold.
3160 if (distOverThreshold >= 2) {
3161 if (currentFingerCount > 2) {
3162 // There are more than two pointers, switch to FREEFORM.
3163 ALOGD_IF(DEBUG_GESTURES,
3164 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3165 currentFingerCount);
3166 *cancelPreviousGesture = true;
3167 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3168 } else {
3169 // There are exactly two pointers.
3170 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3171 uint32_t id1 = idBits.clearFirstMarkedBit();
3172 uint32_t id2 = idBits.firstMarkedBit();
3173 const RawPointerData::Pointer& p1 =
3174 mCurrentRawState.rawPointerData.pointerForId(id1);
3175 const RawPointerData::Pointer& p2 =
3176 mCurrentRawState.rawPointerData.pointerForId(id2);
3177 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3178 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3179 // There are two pointers but they are too far apart for a SWIPE,
3180 // switch to FREEFORM.
3181 ALOGD_IF(DEBUG_GESTURES,
3182 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3183 mutualDistance, mPointerGestureMaxSwipeWidth);
3184 *cancelPreviousGesture = true;
3185 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3186 } else {
3187 // There are two pointers. Wait for both pointers to start moving
3188 // before deciding whether this is a SWIPE or FREEFORM gesture.
3189 float dist1 = dist[id1];
3190 float dist2 = dist[id2];
3191 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3192 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3193 // Calculate the dot product of the displacement vectors.
3194 // When the vectors are oriented in approximately the same direction,
3195 // the angle betweeen them is near zero and the cosine of the angle
3196 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3197 // mag(v2).
3198 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3199 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3200 float dx1 = delta1.dx * mPointerXZoomScale;
3201 float dy1 = delta1.dy * mPointerYZoomScale;
3202 float dx2 = delta2.dx * mPointerXZoomScale;
3203 float dy2 = delta2.dy * mPointerYZoomScale;
3204 float dot = dx1 * dx2 + dy1 * dy2;
3205 float cosine = dot / (dist1 * dist2); // denominator always > 0
3206 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3207 // Pointers are moving in the same direction. Switch to SWIPE.
3208 ALOGD_IF(DEBUG_GESTURES,
3209 "Gestures: PRESS transitioned to SWIPE, "
3210 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3211 "cosine %0.3f >= %0.3f",
3212 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3213 mConfig.pointerGestureMultitouchMinDistance, cosine,
3214 mConfig.pointerGestureSwipeTransitionAngleCosine);
3215 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3216 } else {
3217 // Pointers are moving in different directions. Switch to FREEFORM.
3218 ALOGD_IF(DEBUG_GESTURES,
3219 "Gestures: PRESS transitioned to FREEFORM, "
3220 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3221 "cosine %0.3f < %0.3f",
3222 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3223 mConfig.pointerGestureMultitouchMinDistance, cosine,
3224 mConfig.pointerGestureSwipeTransitionAngleCosine);
3225 *cancelPreviousGesture = true;
3226 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3227 }
3228 }
3229 }
3230 }
3231 }
3232 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3233 // Switch from SWIPE to FREEFORM if additional pointers go down.
3234 // Cancel previous gesture.
3235 if (currentFingerCount > 2) {
3236 ALOGD_IF(DEBUG_GESTURES,
3237 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3238 currentFingerCount);
3239 *cancelPreviousGesture = true;
3240 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3241 }
3242 }
3243
3244 // Move the reference points based on the overall group motion of the fingers
3245 // except in PRESS mode while waiting for a transition to occur.
3246 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3247 (commonDeltaRawX || commonDeltaRawY)) {
3248 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3249 uint32_t id = idBits.clearFirstMarkedBit();
3250 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3251 delta.dx = 0;
3252 delta.dy = 0;
3253 }
3254
3255 mPointerGesture.referenceTouchX += commonDeltaRawX;
3256 mPointerGesture.referenceTouchY += commonDeltaRawY;
3257
3258 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3259 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3260
3261 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3262 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3263
3264 mPointerGesture.referenceGestureX += commonDeltaX;
3265 mPointerGesture.referenceGestureY += commonDeltaY;
3266 }
3267
3268 // Report gestures.
3269 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3270 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3271 // PRESS or SWIPE mode.
3272 ALOGD_IF(DEBUG_GESTURES,
3273 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3274 "currentTouchPointerCount=%d",
3275 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3276 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3277
3278 mPointerGesture.currentGestureIdBits.clear();
3279 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3280 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3281 mPointerGesture.currentGestureProperties[0].clear();
3282 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3283 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3284 mPointerGesture.currentGestureCoords[0].clear();
3285 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3286 mPointerGesture.referenceGestureX);
3287 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3288 mPointerGesture.referenceGestureY);
3289 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3290 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3291 float xOffset = static_cast<float>(commonDeltaRawX) /
3292 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3293 float yOffset = static_cast<float>(commonDeltaRawY) /
3294 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3295 mPointerGesture.currentGestureCoords[0]
3296 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3297 mPointerGesture.currentGestureCoords[0]
3298 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3299 }
3300 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3301 // FREEFORM mode.
3302 ALOGD_IF(DEBUG_GESTURES,
3303 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3304 "currentTouchPointerCount=%d",
3305 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3306 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3307
3308 mPointerGesture.currentGestureIdBits.clear();
3309
3310 BitSet32 mappedTouchIdBits;
3311 BitSet32 usedGestureIdBits;
3312 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3313 // Initially, assign the active gesture id to the active touch point
3314 // if there is one. No other touch id bits are mapped yet.
3315 if (!*cancelPreviousGesture) {
3316 mappedTouchIdBits.markBit(activeTouchId);
3317 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3318 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3319 mPointerGesture.activeGestureId;
3320 } else {
3321 mPointerGesture.activeGestureId = -1;
3322 }
3323 } else {
3324 // Otherwise, assume we mapped all touches from the previous frame.
3325 // Reuse all mappings that are still applicable.
3326 mappedTouchIdBits.value =
3327 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3328 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3329
3330 // Check whether we need to choose a new active gesture id because the
3331 // current went went up.
3332 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3333 ~mCurrentCookedState.fingerIdBits.value);
3334 !upTouchIdBits.isEmpty();) {
3335 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3336 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3337 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3338 mPointerGesture.activeGestureId = -1;
3339 break;
3340 }
3341 }
3342 }
3343
3344 ALOGD_IF(DEBUG_GESTURES,
3345 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3346 "activeGestureId=%d",
3347 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3348
3349 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3350 for (uint32_t i = 0; i < currentFingerCount; i++) {
3351 uint32_t touchId = idBits.clearFirstMarkedBit();
3352 uint32_t gestureId;
3353 if (!mappedTouchIdBits.hasBit(touchId)) {
3354 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3355 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3356 ALOGD_IF(DEBUG_GESTURES,
3357 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3358 gestureId);
3359 } else {
3360 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3361 ALOGD_IF(DEBUG_GESTURES,
3362 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3363 touchId, gestureId);
3364 }
3365 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3366 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3367
3368 const RawPointerData::Pointer& pointer =
3369 mCurrentRawState.rawPointerData.pointerForId(touchId);
3370 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3371 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3372 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3373
3374 mPointerGesture.currentGestureProperties[i].clear();
3375 mPointerGesture.currentGestureProperties[i].id = gestureId;
3376 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3377 mPointerGesture.currentGestureCoords[i].clear();
3378 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3379 mPointerGesture.referenceGestureX +
3380 deltaX);
3381 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3382 mPointerGesture.referenceGestureY +
3383 deltaY);
3384 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3385 }
3386
3387 if (mPointerGesture.activeGestureId < 0) {
3388 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3389 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3390 mPointerGesture.activeGestureId);
3391 }
3392 }
3393}
3394
Harry Cutts714d1ad2022-08-24 16:36:43 +00003395void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3396 const RawPointerData::Pointer& currentPointer =
3397 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3398 const RawPointerData::Pointer& lastPointer =
3399 mLastRawState.rawPointerData.pointerForId(pointerId);
3400 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3401 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3402
3403 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3404 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3405
3406 mPointerController->move(deltaX, deltaY);
3407}
3408
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003409std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3410 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003411 mPointerSimple.currentCoords.clear();
3412 mPointerSimple.currentProperties.clear();
3413
3414 bool down, hovering;
3415 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3416 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3417 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003418 mPointerController
3419 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3420 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003421
3422 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3423 down = !hovering;
3424
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003425 float x, y;
3426 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003427 mPointerSimple.currentCoords.copyFrom(
3428 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3429 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3430 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3431 mPointerSimple.currentProperties.id = 0;
3432 mPointerSimple.currentProperties.toolType =
3433 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3434 } else {
3435 down = false;
3436 hovering = false;
3437 }
3438
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003439 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003440}
3441
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003442std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3443 uint32_t policyFlags) {
3444 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003445}
3446
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003447std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3448 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003449 mPointerSimple.currentCoords.clear();
3450 mPointerSimple.currentProperties.clear();
3451
3452 bool down, hovering;
3453 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3454 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003455 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003456 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003457 } else {
3458 mPointerVelocityControl.reset();
3459 }
3460
3461 down = isPointerDown(mCurrentRawState.buttonState);
3462 hovering = !down;
3463
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003464 float x, y;
3465 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003466 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003467 mPointerSimple.currentCoords.copyFrom(
3468 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3469 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3470 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3471 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3472 hovering ? 0.0f : 1.0f);
3473 mPointerSimple.currentProperties.id = 0;
3474 mPointerSimple.currentProperties.toolType =
3475 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3476 } else {
3477 mPointerVelocityControl.reset();
3478
3479 down = false;
3480 hovering = false;
3481 }
3482
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003483 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003484}
3485
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003486std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3487 uint32_t policyFlags) {
3488 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003489
3490 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003491
3492 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003493}
3494
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003495std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3496 uint32_t policyFlags, bool down,
3497 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003498 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3499 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003500 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003501 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003502
3503 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003504 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003505 mPointerController->clearSpots();
3506 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003507 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003508 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003509 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003510 }
Garfield Tan9514d782020-11-10 16:37:23 -08003511 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003512
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003513 float xCursorPosition, yCursorPosition;
3514 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003515
3516 if (mPointerSimple.down && !down) {
3517 mPointerSimple.down = false;
3518
3519 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003520 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3521 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3522 0, metaState, mLastRawState.buttonState,
3523 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3524 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3525 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3526 yCursorPosition, mPointerSimple.downTime,
3527 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003528 }
3529
3530 if (mPointerSimple.hovering && !hovering) {
3531 mPointerSimple.hovering = false;
3532
3533 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003534 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3535 mSource, displayId, policyFlags,
3536 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3537 mLastRawState.buttonState, MotionClassification::NONE,
3538 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3539 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3540 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3541 yCursorPosition, mPointerSimple.downTime,
3542 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003543 }
3544
3545 if (down) {
3546 if (!mPointerSimple.down) {
3547 mPointerSimple.down = true;
3548 mPointerSimple.downTime = when;
3549
3550 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003551 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3552 mSource, displayId, policyFlags,
3553 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3554 mCurrentRawState.buttonState, MotionClassification::NONE,
3555 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3556 &mPointerSimple.currentProperties,
3557 &mPointerSimple.currentCoords, mOrientedXPrecision,
3558 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3559 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003560 }
3561
3562 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003563 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3564 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3565 0, 0, metaState, mCurrentRawState.buttonState,
3566 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3567 &mPointerSimple.currentProperties,
3568 &mPointerSimple.currentCoords, mOrientedXPrecision,
3569 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3570 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003571 }
3572
3573 if (hovering) {
3574 if (!mPointerSimple.hovering) {
3575 mPointerSimple.hovering = true;
3576
3577 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003578 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3579 mSource, displayId, policyFlags,
3580 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3581 mCurrentRawState.buttonState, MotionClassification::NONE,
3582 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3583 &mPointerSimple.currentProperties,
3584 &mPointerSimple.currentCoords, mOrientedXPrecision,
3585 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3586 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003587 }
3588
3589 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003590 out.push_back(
3591 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3592 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3593 metaState, mCurrentRawState.buttonState,
3594 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3595 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3596 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3597 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003598 }
3599
3600 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3601 float vscroll = mCurrentRawState.rawVScroll;
3602 float hscroll = mCurrentRawState.rawHScroll;
3603 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3604 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3605
3606 // Send scroll.
3607 PointerCoords pointerCoords;
3608 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3609 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3610 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3611
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003612 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3613 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3614 0, 0, metaState, mCurrentRawState.buttonState,
3615 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3616 &mPointerSimple.currentProperties, &pointerCoords,
3617 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3618 yCursorPosition, mPointerSimple.downTime,
3619 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003620 }
3621
3622 // Save state.
3623 if (down || hovering) {
3624 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3625 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003626 mPointerSimple.displayId = displayId;
3627 mPointerSimple.source = mSource;
3628 mPointerSimple.lastCursorX = xCursorPosition;
3629 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003630 } else {
3631 mPointerSimple.reset();
3632 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003633 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003634}
3635
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003636std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3637 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003638 std::list<NotifyArgs> out;
3639 if (mPointerSimple.down || mPointerSimple.hovering) {
3640 int32_t metaState = getContext()->getGlobalMetaState();
3641 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3642 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3643 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3644 metaState, mLastRawState.buttonState,
3645 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3646 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3647 mOrientedXPrecision, mOrientedYPrecision,
3648 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3649 mPointerSimple.downTime,
3650 /* videoFrames */ {}));
3651 if (mPointerController != nullptr) {
3652 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3653 }
3654 }
3655 mPointerSimple.reset();
3656 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003657}
3658
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003659static bool isStylusEvent(uint32_t source, int32_t action, const PointerProperties* properties) {
3660 if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
3661 return false;
3662 }
3663 const auto actionIndex = action >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3664 return isStylusToolType(properties[actionIndex].toolType);
3665}
3666
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003667NotifyMotionArgs TouchInputMapper::dispatchMotion(
3668 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3669 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003670 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3671 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003672 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003673 PointerCoords pointerCoords[MAX_POINTERS];
3674 PointerProperties pointerProperties[MAX_POINTERS];
3675 uint32_t pointerCount = 0;
3676 while (!idBits.isEmpty()) {
3677 uint32_t id = idBits.clearFirstMarkedBit();
3678 uint32_t index = idToIndex[id];
3679 pointerProperties[pointerCount].copyFrom(properties[index]);
3680 pointerCoords[pointerCount].copyFrom(coords[index]);
3681
3682 if (changedId >= 0 && id == uint32_t(changedId)) {
3683 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3684 }
3685
3686 pointerCount += 1;
3687 }
3688
3689 ALOG_ASSERT(pointerCount != 0);
3690
3691 if (changedId >= 0 && pointerCount == 1) {
3692 // Replace initial down and final up action.
3693 // We can compare the action without masking off the changed pointer index
3694 // because we know the index is 0.
3695 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3696 action = AMOTION_EVENT_ACTION_DOWN;
3697 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003698 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3699 action = AMOTION_EVENT_ACTION_CANCEL;
3700 } else {
3701 action = AMOTION_EVENT_ACTION_UP;
3702 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003703 } else {
3704 // Can't happen.
3705 ALOG_ASSERT(false);
3706 }
3707 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003708
3709 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3710 const bool showDirectStylusPointer = mConfig.stylusPointerIconEnabled &&
3711 mDeviceMode == DeviceMode::DIRECT && isStylusEvent(source, action, pointerProperties) &&
3712 displayId != ADISPLAY_ID_NONE && displayId == mPointerController->getDisplayId();
3713 if (showDirectStylusPointer) {
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003714 switch (action & AMOTION_EVENT_ACTION_MASK) {
3715 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3716 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3717 mPointerController->setPresentation(
Seunghwan Choi75789cd2023-01-13 20:31:59 +09003718 PointerControllerInterface::Presentation::STYLUS_HOVER);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003719 mPointerController
3720 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[0].getX(),
3721 mCurrentCookedState.cookedPointerData.pointerCoords[0]
3722 .getY());
3723 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3724 break;
3725 case AMOTION_EVENT_ACTION_HOVER_EXIT:
3726 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
3727 break;
3728 }
3729 }
3730
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003731 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3732 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003733 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003734 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003735 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003736 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003737 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003738 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003739 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003740 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3741 policyFlags, action, actionButton, flags, metaState, buttonState,
3742 classification, edgeFlags, pointerCount, pointerProperties,
3743 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3744 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003745}
3746
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003747std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3748 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003749 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3750 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003751 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003752}
3753
Prabir Pradhan1728b212021-10-19 16:00:03 -07003754bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003755 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003756 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003757 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003758}
3759
3760const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3761 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003762 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3763 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3764 "left=%d, top=%d, right=%d, bottom=%d",
3765 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3766 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003767
3768 if (virtualKey.isHit(x, y)) {
3769 return &virtualKey;
3770 }
3771 }
3772
3773 return nullptr;
3774}
3775
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003776void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3777 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3778 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003779
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003780 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003781
3782 if (currentPointerCount == 0) {
3783 // No pointers to assign.
3784 return;
3785 }
3786
3787 if (lastPointerCount == 0) {
3788 // All pointers are new.
3789 for (uint32_t i = 0; i < currentPointerCount; i++) {
3790 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003791 current.rawPointerData.pointers[i].id = id;
3792 current.rawPointerData.idToIndex[id] = i;
3793 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003794 }
3795 return;
3796 }
3797
3798 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003799 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003800 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003801 uint32_t id = last.rawPointerData.pointers[0].id;
3802 current.rawPointerData.pointers[0].id = id;
3803 current.rawPointerData.idToIndex[id] = 0;
3804 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003805 return;
3806 }
3807
3808 // General case.
3809 // We build a heap of squared euclidean distances between current and last pointers
3810 // associated with the current and last pointer indices. Then, we find the best
3811 // match (by distance) for each current pointer.
3812 // The pointers must have the same tool type but it is possible for them to
3813 // transition from hovering to touching or vice-versa while retaining the same id.
3814 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3815
3816 uint32_t heapSize = 0;
3817 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3818 currentPointerIndex++) {
3819 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3820 lastPointerIndex++) {
3821 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003822 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003823 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003824 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003825 if (currentPointer.toolType == lastPointer.toolType) {
3826 int64_t deltaX = currentPointer.x - lastPointer.x;
3827 int64_t deltaY = currentPointer.y - lastPointer.y;
3828
3829 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3830
3831 // Insert new element into the heap (sift up).
3832 heap[heapSize].currentPointerIndex = currentPointerIndex;
3833 heap[heapSize].lastPointerIndex = lastPointerIndex;
3834 heap[heapSize].distance = distance;
3835 heapSize += 1;
3836 }
3837 }
3838 }
3839
3840 // Heapify
3841 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3842 startIndex -= 1;
3843 for (uint32_t parentIndex = startIndex;;) {
3844 uint32_t childIndex = parentIndex * 2 + 1;
3845 if (childIndex >= heapSize) {
3846 break;
3847 }
3848
3849 if (childIndex + 1 < heapSize &&
3850 heap[childIndex + 1].distance < heap[childIndex].distance) {
3851 childIndex += 1;
3852 }
3853
3854 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3855 break;
3856 }
3857
3858 swap(heap[parentIndex], heap[childIndex]);
3859 parentIndex = childIndex;
3860 }
3861 }
3862
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003863 if (DEBUG_POINTER_ASSIGNMENT) {
3864 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3865 for (size_t i = 0; i < heapSize; i++) {
3866 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3867 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3868 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003869 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003870
3871 // Pull matches out by increasing order of distance.
3872 // To avoid reassigning pointers that have already been matched, the loop keeps track
3873 // of which last and current pointers have been matched using the matchedXXXBits variables.
3874 // It also tracks the used pointer id bits.
3875 BitSet32 matchedLastBits(0);
3876 BitSet32 matchedCurrentBits(0);
3877 BitSet32 usedIdBits(0);
3878 bool first = true;
3879 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3880 while (heapSize > 0) {
3881 if (first) {
3882 // The first time through the loop, we just consume the root element of
3883 // the heap (the one with smallest distance).
3884 first = false;
3885 } else {
3886 // Previous iterations consumed the root element of the heap.
3887 // Pop root element off of the heap (sift down).
3888 heap[0] = heap[heapSize];
3889 for (uint32_t parentIndex = 0;;) {
3890 uint32_t childIndex = parentIndex * 2 + 1;
3891 if (childIndex >= heapSize) {
3892 break;
3893 }
3894
3895 if (childIndex + 1 < heapSize &&
3896 heap[childIndex + 1].distance < heap[childIndex].distance) {
3897 childIndex += 1;
3898 }
3899
3900 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3901 break;
3902 }
3903
3904 swap(heap[parentIndex], heap[childIndex]);
3905 parentIndex = childIndex;
3906 }
3907
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003908 if (DEBUG_POINTER_ASSIGNMENT) {
3909 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3910 for (size_t j = 0; j < heapSize; j++) {
3911 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3912 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3913 heap[j].distance);
3914 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003915 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003916 }
3917
3918 heapSize -= 1;
3919
3920 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3921 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3922
3923 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3924 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3925
3926 matchedCurrentBits.markBit(currentPointerIndex);
3927 matchedLastBits.markBit(lastPointerIndex);
3928
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003929 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3930 current.rawPointerData.pointers[currentPointerIndex].id = id;
3931 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3932 current.rawPointerData.markIdBit(id,
3933 current.rawPointerData.isHovering(
3934 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003935 usedIdBits.markBit(id);
3936
Harry Cutts45483602022-08-24 14:36:48 +00003937 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3938 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3939 ", distance=%" PRIu64,
3940 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003941 break;
3942 }
3943 }
3944
3945 // Assign fresh ids to pointers that were not matched in the process.
3946 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3947 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3948 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3949
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003950 current.rawPointerData.pointers[currentPointerIndex].id = id;
3951 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3952 current.rawPointerData.markIdBit(id,
3953 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003954
Harry Cutts45483602022-08-24 14:36:48 +00003955 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3956 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
3957 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003958 }
3959}
3960
3961int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3962 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3963 return AKEY_STATE_VIRTUAL;
3964 }
3965
3966 for (const VirtualKey& virtualKey : mVirtualKeys) {
3967 if (virtualKey.keyCode == keyCode) {
3968 return AKEY_STATE_UP;
3969 }
3970 }
3971
3972 return AKEY_STATE_UNKNOWN;
3973}
3974
3975int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3976 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3977 return AKEY_STATE_VIRTUAL;
3978 }
3979
3980 for (const VirtualKey& virtualKey : mVirtualKeys) {
3981 if (virtualKey.scanCode == scanCode) {
3982 return AKEY_STATE_UP;
3983 }
3984 }
3985
3986 return AKEY_STATE_UNKNOWN;
3987}
3988
Siarhei Vishniakou74007942022-06-13 13:57:47 -07003989bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
3990 const std::vector<int32_t>& keyCodes,
3991 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003992 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07003993 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003994 if (virtualKey.keyCode == keyCodes[i]) {
3995 outFlags[i] = 1;
3996 }
3997 }
3998 }
3999
4000 return true;
4001}
4002
4003std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4004 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004005 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004006 return std::make_optional(mPointerController->getDisplayId());
4007 } else {
4008 return std::make_optional(mViewport.displayId);
4009 }
4010 }
4011 return std::nullopt;
4012}
4013
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004014} // namespace android