blob: 509c2e80986073c3512175fb5bdc3f407457381d [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
Ambrus Weisz7b6e16b2022-12-16 17:54:57 +0000296 // Full configuration should happen the first time configure is called and
297 // when the device type is changed. Changing a device type can affect
298 // various other parameters so should result in a reconfiguration.
299 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_TYPE)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700300 // Configure basic parameters.
301 configureParameters();
302
303 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800304 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000305 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700306
307 // Configure absolute axis information.
308 configureRawPointerAxes();
309
310 // Prepare input device calibration.
311 parseCalibration();
312 resolveCalibration();
313 }
314
315 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
316 // Update location calibration to reflect current settings
317 updateAffineTransformation();
318 }
319
320 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
321 // Update pointer speed.
322 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
323 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
324 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
325 }
326
327 bool resetNeeded = false;
328 if (!changes ||
329 (changes &
330 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800331 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700332 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
333 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
Ambrus Weisz7b6e16b2022-12-16 17:54:57 +0000334 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE |
335 InputReaderConfiguration::CHANGE_DEVICE_TYPE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700336 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700337 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700338 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700339 }
340
341 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700342 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000343
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700344 // Send reset, unless this is the first time the device has been configured,
345 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000346 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700347 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700348 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700349}
350
351void TouchInputMapper::resolveExternalStylusPresence() {
352 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800353 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700354 mExternalStylusConnected = !devices.empty();
355
356 if (!mExternalStylusConnected) {
357 resetExternalStylus();
358 }
359}
360
361void TouchInputMapper::configureParameters() {
362 // Use the pointer presentation mode for devices that do not support distinct
363 // multitouch. The spot-based presentation relies on being able to accurately
364 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800365 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100366 ? Parameters::GestureMode::SINGLE_TOUCH
367 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700368
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700369 std::string gestureModeString;
370 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800371 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700372 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100373 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700374 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100375 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700376 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700377 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700378 }
379 }
380
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000381 configureDeviceType();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700382
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800383 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700384
Michael Wright227c5542020-07-02 18:30:52 +0100385 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700386 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800387 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700388
Michael Wrighta9cf4192022-12-01 23:46:39 +0000389 mParameters.orientation = ui::ROTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700390 std::string orientationString;
391 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700392 orientationString)) {
393 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
394 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
395 } else if (orientationString == "ORIENTATION_90") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000396 mParameters.orientation = ui::ROTATION_90;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700397 } else if (orientationString == "ORIENTATION_180") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000398 mParameters.orientation = ui::ROTATION_180;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700399 } else if (orientationString == "ORIENTATION_270") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000400 mParameters.orientation = ui::ROTATION_270;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700401 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700402 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700403 }
404 }
405
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700406 mParameters.hasAssociatedDisplay = false;
407 mParameters.associatedDisplayIsExternal = false;
408 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100409 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000410 mParameters.deviceType == Parameters::DeviceType::POINTER ||
411 (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
412 getDeviceContext().getAssociatedViewport())) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700413 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100414 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800415 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700416 std::string uniqueDisplayId;
417 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800418 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700419 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
420 }
421 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800422 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700423 mParameters.hasAssociatedDisplay = true;
424 }
425
426 // Initial downs on external touch devices should wake the device.
427 // Normally we don't do this for internal touch screens to prevent them from waking
428 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800429 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700430 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000431
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000432 InputDeviceUsiVersion usiVersion;
433 if (getDeviceContext().getConfiguration().tryGetProperty("touch.usiVersionMajor",
434 usiVersion.majorVersion) &&
435 getDeviceContext().getConfiguration().tryGetProperty("touch.usiVersionMinor",
436 usiVersion.minorVersion)) {
437 mParameters.usiVersion = usiVersion;
438 }
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700439
440 mParameters.enableForInactiveViewport = false;
441 getDeviceContext().getConfiguration().tryGetProperty("touch.enableForInactiveViewport",
442 mParameters.enableForInactiveViewport);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700443}
444
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000445void TouchInputMapper::configureDeviceType() {
446 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
447 // The device is a touch screen.
448 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
449 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
450 // The device is a pointing device like a track pad.
451 mParameters.deviceType = Parameters::DeviceType::POINTER;
452 } else {
453 // The device is a touch pad of unknown purpose.
454 mParameters.deviceType = Parameters::DeviceType::POINTER;
455 }
456
457 // Type association takes precedence over the device type found in the idc file.
458 std::string deviceTypeString = getDeviceContext().getDeviceTypeAssociation().value_or("");
459 if (deviceTypeString.empty()) {
460 getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType", deviceTypeString);
461 }
462 if (deviceTypeString == "touchScreen") {
463 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
464 } else if (deviceTypeString == "touchNavigation") {
465 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
466 } else if (deviceTypeString == "pointer") {
467 mParameters.deviceType = Parameters::DeviceType::POINTER;
468 } else if (deviceTypeString != "default" && deviceTypeString != "") {
469 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
470 }
471}
472
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700473void TouchInputMapper::dumpParameters(std::string& dump) {
474 dump += INDENT3 "Parameters:\n";
475
Dominik Laskowski75788452021-02-09 18:51:25 -0800476 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700477
Dominik Laskowski75788452021-02-09 18:51:25 -0800478 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700479
480 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
481 "displayId='%s'\n",
482 toString(mParameters.hasAssociatedDisplay),
483 toString(mParameters.associatedDisplayIsExternal),
484 mParameters.uniqueDisplayId.c_str());
485 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800486 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000487 dump += StringPrintf(INDENT4 "UsiVersion: %s\n",
488 toString(mParameters.usiVersion, toString).c_str());
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700489 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
490 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700491}
492
493void TouchInputMapper::configureRawPointerAxes() {
494 mRawPointerAxes.clear();
495}
496
497void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
498 dump += INDENT3 "Raw Touch Axes:\n";
499 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
500 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
501 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
502 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
503 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
504 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
505 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
506 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
507 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
508 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
509 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
510 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
511 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
512}
513
514bool TouchInputMapper::hasExternalStylus() const {
515 return mExternalStylusConnected;
516}
517
518/**
519 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000520 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800521 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000522 * 3. Get the matching viewport by either unique id in idc file or by the display type
523 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800524 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700525 */
526std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800527 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000528 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800529 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700530 }
531
Christine Franks2a2293c2022-01-18 11:51:16 -0800532 const std::optional<std::string> associatedDisplayUniqueId =
533 getDeviceContext().getAssociatedDisplayUniqueId();
534 if (associatedDisplayUniqueId) {
535 return getDeviceContext().getAssociatedViewport();
536 }
537
Michael Wright227c5542020-07-02 18:30:52 +0100538 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800539 std::optional<DisplayViewport> viewport =
540 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
541 if (viewport) {
542 return viewport;
543 } else {
544 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
545 mConfig.defaultPointerDisplayId);
546 }
547 }
548
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700549 // Check if uniqueDisplayId is specified in idc file.
550 if (!mParameters.uniqueDisplayId.empty()) {
551 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
552 }
553
554 ViewportType viewportTypeToUse;
555 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100556 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700557 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100558 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700559 }
560
561 std::optional<DisplayViewport> viewport =
562 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100563 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700564 ALOGW("Input device %s should be associated with external display, "
565 "fallback to internal one for the external viewport is not found.",
566 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100567 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700568 }
569
570 return viewport;
571 }
572
573 // No associated display, return a non-display viewport.
574 DisplayViewport newViewport;
575 // Raw width and height in the natural orientation.
576 int32_t rawWidth = mRawPointerAxes.getRawWidth();
577 int32_t rawHeight = mRawPointerAxes.getRawHeight();
578 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
579 return std::make_optional(newViewport);
580}
581
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800582int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
583 if (resolution < 0) {
584 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
585 getDeviceName().c_str());
586 return 0;
587 }
588 return resolution;
589}
590
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800591void TouchInputMapper::initializeSizeRanges() {
592 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
593 mSizeScale = 0.0f;
594 return;
595 }
596
597 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000598 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800599
600 // Size factors.
601 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
602 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
603 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
604 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
605 } else {
606 mSizeScale = 0.0f;
607 }
608
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700609 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
610 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
611 .source = mSource,
612 .min = 0,
613 .max = diagonalSize,
614 .flat = 0,
615 .fuzz = 0,
616 .resolution = 0,
617 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800618
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800619 if (mRawPointerAxes.touchMajor.valid) {
620 mRawPointerAxes.touchMajor.resolution =
621 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700622 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800623 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800624
625 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700626 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800627 if (mRawPointerAxes.touchMinor.valid) {
628 mRawPointerAxes.touchMinor.resolution =
629 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700630 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800631 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800632
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700633 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
634 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
635 .source = mSource,
636 .min = 0,
637 .max = diagonalSize,
638 .flat = 0,
639 .fuzz = 0,
640 .resolution = 0,
641 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800642 if (mRawPointerAxes.toolMajor.valid) {
643 mRawPointerAxes.toolMajor.resolution =
644 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700645 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800646 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800647
648 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700649 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800650 if (mRawPointerAxes.toolMinor.valid) {
651 mRawPointerAxes.toolMinor.resolution =
652 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700653 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800654 }
655
656 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700657 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
658 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
659 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
660 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800661 } else {
662 // Support for other calibrations can be added here.
663 ALOGW("%s calibration is not supported for size ranges at the moment. "
664 "Using raw resolution instead",
665 ftl::enum_string(mCalibration.sizeCalibration).c_str());
666 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800667
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700668 mOrientedRanges.size = InputDeviceInfo::MotionRange{
669 .axis = AMOTION_EVENT_AXIS_SIZE,
670 .source = mSource,
671 .min = 0,
672 .max = 1.0,
673 .flat = 0,
674 .fuzz = 0,
675 .resolution = 0,
676 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800677}
678
679void TouchInputMapper::initializeOrientedRanges() {
680 // Configure X and Y factors.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000681 const float orientedScaleX = mRawToDisplay.getScaleX();
682 const float orientedScaleY = mRawToDisplay.getScaleY();
683 mOrientedXPrecision = 1.0f / orientedScaleX;
684 mOrientedYPrecision = 1.0f / orientedScaleY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800685
686 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
687 mOrientedRanges.x.source = mSource;
688 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
689 mOrientedRanges.y.source = mSource;
690
691 // Scale factor for terms that are not oriented in a particular axis.
692 // If the pixels are square then xScale == yScale otherwise we fake it
693 // by choosing an average.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000694 mGeometricScale = avg(orientedScaleX, orientedScaleY);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800695
696 initializeSizeRanges();
697
698 // Pressure factors.
699 mPressureScale = 0;
700 float pressureMax = 1.0;
701 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
702 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700703 if (mCalibration.pressureScale) {
704 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800705 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
706 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
707 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
708 }
709 }
710
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700711 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
712 .axis = AMOTION_EVENT_AXIS_PRESSURE,
713 .source = mSource,
714 .min = 0,
715 .max = pressureMax,
716 .flat = 0,
717 .fuzz = 0,
718 .resolution = 0,
719 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800720
721 // Tilt
722 mTiltXCenter = 0;
723 mTiltXScale = 0;
724 mTiltYCenter = 0;
725 mTiltYScale = 0;
726 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
727 if (mHaveTilt) {
728 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
729 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
730 mTiltXScale = M_PI / 180;
731 mTiltYScale = M_PI / 180;
732
733 if (mRawPointerAxes.tiltX.resolution) {
734 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
735 }
736 if (mRawPointerAxes.tiltY.resolution) {
737 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
738 }
739
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700740 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
741 .axis = AMOTION_EVENT_AXIS_TILT,
742 .source = mSource,
743 .min = 0,
744 .max = M_PI_2,
745 .flat = 0,
746 .fuzz = 0,
747 .resolution = 0,
748 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800749 }
750
751 // Orientation
752 mOrientationScale = 0;
753 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700754 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
755 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
756 .source = mSource,
757 .min = -M_PI,
758 .max = M_PI,
759 .flat = 0,
760 .fuzz = 0,
761 .resolution = 0,
762 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800763
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800764 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
765 if (mCalibration.orientationCalibration ==
766 Calibration::OrientationCalibration::INTERPOLATED) {
767 if (mRawPointerAxes.orientation.valid) {
768 if (mRawPointerAxes.orientation.maxValue > 0) {
769 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
770 } else if (mRawPointerAxes.orientation.minValue < 0) {
771 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
772 } else {
773 mOrientationScale = 0;
774 }
775 }
776 }
777
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700778 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
779 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
780 .source = mSource,
781 .min = -M_PI_2,
782 .max = M_PI_2,
783 .flat = 0,
784 .fuzz = 0,
785 .resolution = 0,
786 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800787 }
788
789 // Distance
790 mDistanceScale = 0;
791 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
792 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700793 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800794 }
795
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700796 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800797
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700798 .axis = AMOTION_EVENT_AXIS_DISTANCE,
799 .source = mSource,
800 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
801 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
802 .flat = 0,
803 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
804 .resolution = 0,
805 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800806 }
807
808 // Compute oriented precision, scales and ranges.
809 // Note that the maximum value reported is an inclusive maximum value so it is one
810 // unit less than the total width or height of the display.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000811 // TODO(b/20508709): Calculate the oriented ranges using the input device's raw frame.
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800812 switch (mInputDeviceOrientation) {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000813 case ui::ROTATION_90:
814 case ui::ROTATION_270:
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800815 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000816 mOrientedRanges.x.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800817 mOrientedRanges.x.flat = 0;
818 mOrientedRanges.x.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000819 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mRawToDisplay.getScaleY();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800820
821 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000822 mOrientedRanges.y.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800823 mOrientedRanges.y.flat = 0;
824 mOrientedRanges.y.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000825 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mRawToDisplay.getScaleX();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800826 break;
827
828 default:
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800829 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000830 mOrientedRanges.x.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800831 mOrientedRanges.x.flat = 0;
832 mOrientedRanges.x.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000833 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mRawToDisplay.getScaleX();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800834
835 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000836 mOrientedRanges.y.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800837 mOrientedRanges.y.flat = 0;
838 mOrientedRanges.y.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000839 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mRawToDisplay.getScaleY();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800840 break;
841 }
842}
843
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000844void TouchInputMapper::computeInputTransforms() {
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000845 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
846
847 ui::Size rotatedRawSize = rawSize;
848 if (mInputDeviceOrientation == ui::ROTATION_270 || mInputDeviceOrientation == ui::ROTATION_90) {
849 std::swap(rotatedRawSize.width, rotatedRawSize.height);
850 }
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000851 const auto rotationFlags = ui::Transform::toRotationFlags(-mInputDeviceOrientation);
852 mRawRotation = ui::Transform{rotationFlags};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000853
854 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
855 ui::Transform undoRawOffset;
856 undoRawOffset.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
857
858 // Step 2: Rotate the raw coordinates to the expected orientation.
859 ui::Transform rotate;
860 // When rotating raw coordinates, the raw size will be used as an offset.
861 // Account for the extra unit added to the raw range when the raw size was calculated.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000862 rotate.set(rotationFlags, rotatedRawSize.width - 1, rotatedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000863
864 // Step 3: Scale the raw coordinates to the display space.
865 ui::Transform scaleToDisplay;
866 const float xScale = static_cast<float>(mDisplayBounds.width) / rotatedRawSize.width;
867 const float yScale = static_cast<float>(mDisplayBounds.height) / rotatedRawSize.height;
868 scaleToDisplay.set(xScale, 0, 0, yScale);
869
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000870 mRawToDisplay = (scaleToDisplay * (rotate * undoRawOffset));
871
872 // Calculate the transform that takes raw coordinates to the rotated display space.
873 ui::Transform displayToRotatedDisplay;
874 displayToRotatedDisplay.set(ui::Transform::toRotationFlags(-mViewport.orientation),
875 mViewport.deviceWidth, mViewport.deviceHeight);
876 mRawToRotatedDisplay = displayToRotatedDisplay * mRawToDisplay;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000877}
878
Prabir Pradhan1728b212021-10-19 16:00:03 -0700879void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000880 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700881
882 resolveExternalStylusPresence();
883
884 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100885 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000886 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700887 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100888 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700889 if (hasStylus()) {
890 mSource |= AINPUT_SOURCE_STYLUS;
891 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800892 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700893 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100894 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700895 if (hasStylus()) {
896 mSource |= AINPUT_SOURCE_STYLUS;
897 }
898 if (hasExternalStylus()) {
899 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
900 }
Michael Wright227c5542020-07-02 18:30:52 +0100901 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700902 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100903 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700904 } else {
905 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100906 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700907 }
908
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000909 const std::optional<DisplayViewport> newViewportOpt = findViewport();
910
911 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700912 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
913 ALOGW("Touch device '%s' did not report support for X or Y axis! "
914 "The device will be inoperable.",
915 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100916 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000917 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700918 ALOGI("Touch device '%s' could not query the properties of its associated "
919 "display. The device will be inoperable until the display size "
920 "becomes available.",
921 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100922 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700923 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000924 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
925 getDeviceName().c_str(), getDeviceId());
926 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000927 }
928
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700929 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000930 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000931 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
932 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
933 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
934 const float rawMeanResolution =
935 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700936
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000937 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
938 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700939 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700940 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000941 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
942 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
943 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700944
Michael Wright227c5542020-07-02 18:30:52 +0100945 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000946 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700947
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000948 mDisplayBounds = getNaturalDisplaySize(mViewport);
949 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
950 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700951
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000952 // InputReader works in the un-rotated display coordinate space, so we don't need to do
953 // anything if the device is already orientation-aware. If the device is not
954 // orientation-aware, then we need to apply the inverse rotation of the display so that
955 // when the display rotation is applied later as a part of the per-window transform, we
956 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700957 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +0000958 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000959 : getInverseRotation(mViewport.orientation);
960 // For orientation-aware devices that work in the un-rotated coordinate space, the
961 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000962 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000963 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700964
965 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +0000966 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000967 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700968 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000969 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000970 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +0000971 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000972 mRawToDisplay.reset();
973 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000974 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700975 }
976 }
977
978 // If moving between pointer modes, need to reset some state.
979 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
980 if (deviceModeChanged) {
981 mOrientedRanges.clear();
982 }
983
Seunghwan Choi2de48e42023-01-17 20:45:15 +0900984 // Create and preserve the pointer controller in the following cases:
985 const bool isPointerControllerNeeded =
986 // - when the device is in pointer mode, to show the mouse cursor;
987 (mDeviceMode == DeviceMode::POINTER) ||
988 // - when pointer capture is enabled, to preserve the mouse cursor position;
989 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
990 mConfig.pointerCaptureRequest.enable) ||
991 // - when we should be showing touches;
992 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
993 // - when we should be showing a pointer icon for direct styluses.
994 (mDeviceMode == DeviceMode::DIRECT && mConfig.stylusPointerIconEnabled && hasStylus());
995 if (isPointerControllerNeeded) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800996 if (mPointerController == nullptr) {
997 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700998 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000999 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001000 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1001 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001002 } else {
lilinnandef700b2022-06-17 19:32:01 +08001003 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1004 !mConfig.showTouches) {
1005 mPointerController->clearSpots();
1006 }
Michael Wright17db18e2020-06-26 20:51:44 +01001007 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001008 }
1009
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001010 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001011 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001012 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001013 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001014 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001015
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001016 configureVirtualKeys();
1017
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001018 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001019
1020 // Location
1021 updateAffineTransformation();
1022
Michael Wright227c5542020-07-02 18:30:52 +01001023 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001024 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001025 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1026 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001027
1028 // Scale movements such that one whole swipe of the touch pad covers a
1029 // given area relative to the diagonal size of the display when no acceleration
1030 // is applied.
1031 // Assume that the touch pad has a square aspect ratio such that movements in
1032 // X and Y of the same number of raw units cover the same physical distance.
1033 mPointerXMovementScale =
1034 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1035 mPointerYMovementScale = mPointerXMovementScale;
1036
1037 // Scale zooms to cover a smaller range of the display than movements do.
1038 // This value determines the area around the pointer that is affected by freeform
1039 // pointer gestures.
1040 mPointerXZoomScale =
1041 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1042 mPointerYZoomScale = mPointerXZoomScale;
1043
HQ Liue6983c72022-04-19 22:14:56 +00001044 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1045 // axis is non positive value.
1046 const float minFreeformGestureWidth =
1047 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1048
1049 mPointerGestureMaxSwipeWidth =
1050 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1051 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001052 }
1053
1054 // Inform the dispatcher about the changes.
1055 *outResetNeeded = true;
1056 bumpGeneration();
1057 }
1058}
1059
Prabir Pradhan1728b212021-10-19 16:00:03 -07001060void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001061 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001062 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001063 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1064 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001065 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001066}
1067
1068void TouchInputMapper::configureVirtualKeys() {
1069 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001070 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001071
1072 mVirtualKeys.clear();
1073
1074 if (virtualKeyDefinitions.size() == 0) {
1075 return;
1076 }
1077
1078 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1079 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1080 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1081 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1082
1083 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1084 VirtualKey virtualKey;
1085
1086 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1087 int32_t keyCode;
1088 int32_t dummyKeyMetaState;
1089 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001090 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1091 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001092 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1093 continue; // drop the key
1094 }
1095
1096 virtualKey.keyCode = keyCode;
1097 virtualKey.flags = flags;
1098
1099 // convert the key definition's display coordinates into touch coordinates for a hit box
1100 int32_t halfWidth = virtualKeyDefinition.width / 2;
1101 int32_t halfHeight = virtualKeyDefinition.height / 2;
1102
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001103 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1104 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001105 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001106 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1107 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001108 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001109 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1110 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001111 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001112 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1113 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001114 touchScreenTop;
1115 mVirtualKeys.push_back(virtualKey);
1116 }
1117}
1118
1119void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1120 if (!mVirtualKeys.empty()) {
1121 dump += INDENT3 "Virtual Keys:\n";
1122
1123 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1124 const VirtualKey& virtualKey = mVirtualKeys[i];
1125 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1126 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1127 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1128 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1129 }
1130 }
1131}
1132
1133void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001134 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001135 Calibration& out = mCalibration;
1136
1137 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001138 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001139 std::string sizeCalibrationString;
1140 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001141 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001142 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001143 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001144 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001146 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001148 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001149 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001150 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001151 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001152 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001153 }
1154 }
1155
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001156 float sizeScale;
1157
1158 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1159 out.sizeScale = sizeScale;
1160 }
1161 float sizeBias;
1162 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1163 out.sizeBias = sizeBias;
1164 }
1165 bool sizeIsSummed;
1166 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1167 out.sizeIsSummed = sizeIsSummed;
1168 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001169
1170 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001172 std::string pressureCalibrationString;
1173 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001175 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001177 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001178 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001179 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001180 } else if (pressureCalibrationString != "default") {
1181 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001182 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001183 }
1184 }
1185
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001186 float pressureScale;
1187 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1188 out.pressureScale = pressureScale;
1189 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001190
1191 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001192 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001193 std::string orientationCalibrationString;
1194 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001195 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001196 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001197 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001198 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001199 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001201 } else if (orientationCalibrationString != "default") {
1202 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001203 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001204 }
1205 }
1206
1207 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001208 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001209 std::string distanceCalibrationString;
1210 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001212 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001213 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001214 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001215 } else if (distanceCalibrationString != "default") {
1216 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001217 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001218 }
1219 }
1220
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001221 float distanceScale;
1222 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1223 out.distanceScale = distanceScale;
1224 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001225}
1226
1227void TouchInputMapper::resolveCalibration() {
1228 // Size
1229 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001230 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1231 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001232 }
1233 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001234 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001235 }
1236
1237 // Pressure
1238 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001239 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1240 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001241 }
1242 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001243 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001244 }
1245
1246 // Orientation
1247 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001248 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1249 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001250 }
1251 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001252 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001253 }
1254
1255 // Distance
1256 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001257 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1258 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001259 }
1260 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001261 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001262 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001263}
1264
1265void TouchInputMapper::dumpCalibration(std::string& dump) {
1266 dump += INDENT3 "Calibration:\n";
1267
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001268 dump += INDENT4 "touch.size.calibration: ";
1269 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001270
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001271 if (mCalibration.sizeScale) {
1272 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001273 }
1274
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001275 if (mCalibration.sizeBias) {
1276 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001277 }
1278
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001279 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001280 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001281 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001282 }
1283
1284 // Pressure
1285 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001286 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287 dump += INDENT4 "touch.pressure.calibration: none\n";
1288 break;
Michael Wright227c5542020-07-02 18:30:52 +01001289 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001290 dump += INDENT4 "touch.pressure.calibration: physical\n";
1291 break;
Michael Wright227c5542020-07-02 18:30:52 +01001292 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001293 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1294 break;
1295 default:
1296 ALOG_ASSERT(false);
1297 }
1298
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001299 if (mCalibration.pressureScale) {
1300 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 }
1302
1303 // Orientation
1304 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001305 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001306 dump += INDENT4 "touch.orientation.calibration: none\n";
1307 break;
Michael Wright227c5542020-07-02 18:30:52 +01001308 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001309 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1310 break;
Michael Wright227c5542020-07-02 18:30:52 +01001311 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001312 dump += INDENT4 "touch.orientation.calibration: vector\n";
1313 break;
1314 default:
1315 ALOG_ASSERT(false);
1316 }
1317
1318 // Distance
1319 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001320 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001321 dump += INDENT4 "touch.distance.calibration: none\n";
1322 break;
Michael Wright227c5542020-07-02 18:30:52 +01001323 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001324 dump += INDENT4 "touch.distance.calibration: scaled\n";
1325 break;
1326 default:
1327 ALOG_ASSERT(false);
1328 }
1329
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001330 if (mCalibration.distanceScale) {
1331 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001332 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001333}
1334
1335void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1336 dump += INDENT3 "Affine Transformation:\n";
1337
1338 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1339 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1340 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1341 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1342 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1343 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1344}
1345
1346void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001347 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001348 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001349}
1350
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001351std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001352 std::list<NotifyArgs> out = cancelTouch(when, when);
1353 updateTouchSpots();
1354
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001355 mCursorButtonAccumulator.reset(getDeviceContext());
1356 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001357 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001358
1359 mPointerVelocityControl.reset();
1360 mWheelXVelocityControl.reset();
1361 mWheelYVelocityControl.reset();
1362
1363 mRawStatesPending.clear();
1364 mCurrentRawState.clear();
1365 mCurrentCookedState.clear();
1366 mLastRawState.clear();
1367 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001368 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001369 mSentHoverEnter = false;
1370 mHavePointerIds = false;
1371 mCurrentMotionAborted = false;
1372 mDownTime = 0;
1373
1374 mCurrentVirtualKey.down = false;
1375
1376 mPointerGesture.reset();
1377 mPointerSimple.reset();
1378 resetExternalStylus();
1379
1380 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001381 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001382 mPointerController->clearSpots();
1383 }
1384
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001385 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001386}
1387
1388void TouchInputMapper::resetExternalStylus() {
1389 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001390 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001391 mExternalStylusFusionTimeout = LLONG_MAX;
1392 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001393 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001394}
1395
1396void TouchInputMapper::clearStylusDataPendingFlags() {
1397 mExternalStylusDataPending = false;
1398 mExternalStylusFusionTimeout = LLONG_MAX;
1399}
1400
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001401std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001402 mCursorButtonAccumulator.process(rawEvent);
1403 mCursorScrollAccumulator.process(rawEvent);
1404 mTouchButtonAccumulator.process(rawEvent);
1405
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001406 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001407 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001408 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001409 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001410 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001411}
1412
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001413std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1414 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001415 if (mDeviceMode == DeviceMode::DISABLED) {
1416 // Only save the last pending state when the device is disabled.
1417 mRawStatesPending.clear();
1418 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001419 // Push a new state.
1420 mRawStatesPending.emplace_back();
1421
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001422 RawState& next = mRawStatesPending.back();
1423 next.clear();
1424 next.when = when;
1425 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001426
1427 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001428 next.buttonState = filterButtonState(mConfig,
1429 mTouchButtonAccumulator.getButtonState() |
1430 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001431
1432 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001433 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1434 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001435 mCursorScrollAccumulator.finishSync();
1436
1437 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001438 syncTouch(when, &next);
1439
1440 // The last RawState is the actually second to last, since we just added a new state
1441 const RawState& last =
1442 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001443
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001444 std::tie(next.when, next.readTime) =
1445 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1446 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001447
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001448 // Assign pointer ids.
1449 if (!mHavePointerIds) {
1450 assignPointerIds(last, next);
1451 }
1452
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001453 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001454 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1455 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1456 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1457 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1458 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1459 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001460
Arthur Hung9ad18942021-06-19 02:04:46 +00001461 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1462 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1463 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1464 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1465 next.rawPointerData.hoveringIdBits.value);
1466 }
1467
Harry Cutts33476232023-01-30 19:57:29 +00001468 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001469 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001470}
1471
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001472std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1473 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001474 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001475 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001476 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001477 }
1478
1479 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1480 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1481 // touching the current state will only observe the events that have been dispatched to the
1482 // rest of the pipeline.
1483 const size_t N = mRawStatesPending.size();
1484 size_t count;
1485 for (count = 0; count < N; count++) {
1486 const RawState& next = mRawStatesPending[count];
1487
1488 // A failure to assign the stylus id means that we're waiting on stylus data
1489 // and so should defer the rest of the pipeline.
1490 if (assignExternalStylusId(next, timeout)) {
1491 break;
1492 }
1493
1494 // All ready to go.
1495 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001496 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001497 if (mCurrentRawState.when < mLastRawState.when) {
1498 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001499 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001500 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001501 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001502 }
1503 if (count != 0) {
1504 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1505 }
1506
1507 if (mExternalStylusDataPending) {
1508 if (timeout) {
1509 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1510 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001511 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001512 ALOGD_IF(DEBUG_STYLUS_FUSION,
1513 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001514 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001515 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001516 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1517 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1518 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1519 }
1520 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001521 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001522}
1523
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001524std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1525 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001526 // Always start with a clean state.
1527 mCurrentCookedState.clear();
1528
1529 // Apply stylus buttons to current raw state.
1530 applyExternalStylusButtonState(when);
1531
1532 // Handle policy on initial down or hover events.
1533 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1534 mCurrentRawState.rawPointerData.pointerCount != 0;
1535
1536 uint32_t policyFlags = 0;
1537 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1538 if (initialDown || buttonsPressed) {
1539 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001540 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001541 getContext()->fadePointer();
1542 }
1543
1544 if (mParameters.wake) {
1545 policyFlags |= POLICY_FLAG_WAKE;
1546 }
1547 }
1548
1549 // Consume raw off-screen touches before cooking pointer data.
1550 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001551 bool consumed;
1552 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1553 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001554 mCurrentRawState.rawPointerData.clear();
1555 }
1556
1557 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1558 // with cooked pointer data that has the same ids and indices as the raw data.
1559 // The following code can use either the raw or cooked data, as needed.
1560 cookPointerData();
1561
1562 // Apply stylus pressure to current cooked state.
1563 applyExternalStylusTouchState(when);
1564
1565 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001566 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1567 mSource, mViewport.displayId, policyFlags,
1568 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001569
1570 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001571 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001572 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1573 uint32_t id = idBits.clearFirstMarkedBit();
1574 const RawPointerData::Pointer& pointer =
1575 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001576 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001577 mCurrentCookedState.stylusIdBits.markBit(id);
1578 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1579 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1580 mCurrentCookedState.fingerIdBits.markBit(id);
1581 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1582 mCurrentCookedState.mouseIdBits.markBit(id);
1583 }
1584 }
1585 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1586 uint32_t id = idBits.clearFirstMarkedBit();
1587 const RawPointerData::Pointer& pointer =
1588 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001589 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001590 mCurrentCookedState.stylusIdBits.markBit(id);
1591 }
1592 }
1593
1594 // Stylus takes precedence over all tools, then mouse, then finger.
1595 PointerUsage pointerUsage = mPointerUsage;
1596 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1597 mCurrentCookedState.mouseIdBits.clear();
1598 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001599 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001600 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1601 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001602 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001603 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1604 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001605 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001606 }
1607
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001608 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001609 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001610 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001611 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001612 out += dispatchButtonRelease(when, readTime, policyFlags);
1613 out += dispatchHoverExit(when, readTime, policyFlags);
1614 out += dispatchTouches(when, readTime, policyFlags);
1615 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1616 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001617 }
1618
1619 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1620 mCurrentMotionAborted = false;
1621 }
1622 }
1623
1624 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001625 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1626 mSource, mViewport.displayId, policyFlags,
1627 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001628
1629 // Clear some transient state.
1630 mCurrentRawState.rawVScroll = 0;
1631 mCurrentRawState.rawHScroll = 0;
1632
1633 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001634 mLastRawState = mCurrentRawState;
1635 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001636 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001637}
1638
Garfield Tanc734e4f2021-01-15 20:01:39 -08001639void TouchInputMapper::updateTouchSpots() {
1640 if (!mConfig.showTouches || mPointerController == nullptr) {
1641 return;
1642 }
1643
1644 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1645 // clear touch spots.
1646 if (mDeviceMode != DeviceMode::DIRECT &&
1647 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1648 return;
1649 }
1650
1651 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1652 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1653
1654 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001655 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1656 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001657 mCurrentCookedState.cookedPointerData.touchingIdBits,
1658 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001659}
1660
1661bool TouchInputMapper::isTouchScreen() {
1662 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1663 mParameters.hasAssociatedDisplay;
1664}
1665
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001666void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001667 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1668 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001669 const int32_t pressedButtons =
1670 filterButtonState(mConfig,
1671 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001672 const int32_t releasedButtons =
1673 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1674
1675 mCurrentRawState.buttonState |= pressedButtons;
1676 mCurrentRawState.buttonState &= ~releasedButtons;
1677
1678 mExternalStylusButtonsApplied |= pressedButtons;
1679 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001680 }
1681}
1682
1683void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1684 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1685 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001686 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1687 return;
1688 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001689
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001690 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1691 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1692 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1693 : 0.f;
1694 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1695 pressure = *mExternalStylusState.pressure;
1696 }
1697 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1698 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001699
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001700 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001701 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001702 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001703 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001704 }
1705}
1706
1707bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001708 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001709 return false;
1710 }
1711
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001712 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001713 if (mFusedStylusPointerId &&
1714 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001715 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001716 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001717 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001718 }
1719
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001720 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1721 state.rawPointerData.pointerCount != 0;
1722 if (!initialDown) {
1723 return false;
1724 }
1725
1726 if (!mExternalStylusState.pressure) {
1727 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1728 return false;
1729 }
1730
1731 if (*mExternalStylusState.pressure != 0.0f) {
1732 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1733 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1734 return false;
1735 }
1736
1737 if (timeout) {
1738 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1739 mFusedStylusPointerId.reset();
1740 mExternalStylusFusionTimeout = LLONG_MAX;
1741 return false;
1742 }
1743
1744 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1745 // being processed until we either get pressure data or timeout.
1746 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1747 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1748 }
1749 ALOGD_IF(DEBUG_STYLUS_FUSION,
1750 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1751 mExternalStylusFusionTimeout);
1752 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1753 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001754}
1755
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001756std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1757 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001758 if (mDeviceMode == DeviceMode::POINTER) {
1759 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001760 // Since this is a synthetic event, we can consider its latency to be zero
1761 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001762 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001763 }
Michael Wright227c5542020-07-02 18:30:52 +01001764 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001765 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001766 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001767 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1768 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1769 }
1770 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001771 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001772}
1773
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001774std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1775 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001776 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001777 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001778 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001779 // The following three cases are handled here:
1780 // - We're in the middle of a fused stream of data;
1781 // - We're waiting on external stylus data before dispatching the initial down; or
1782 // - Only the button state, which is not reported through a specific pointer, has changed.
1783 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001784 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001785 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001786 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001787 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001788}
1789
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001790std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1791 uint32_t policyFlags, bool& outConsumed) {
1792 outConsumed = false;
1793 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001794 // Check for release of a virtual key.
1795 if (mCurrentVirtualKey.down) {
1796 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1797 // Pointer went up while virtual key was down.
1798 mCurrentVirtualKey.down = false;
1799 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001800 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1801 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1802 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001803 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1804 AKEY_EVENT_FLAG_FROM_SYSTEM |
1805 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001806 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001807 outConsumed = true;
1808 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001809 }
1810
1811 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1812 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1813 const RawPointerData::Pointer& pointer =
1814 mCurrentRawState.rawPointerData.pointerForId(id);
1815 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1816 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1817 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001818 outConsumed = true;
1819 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001820 }
1821 }
1822
1823 // Pointer left virtual key area or another pointer also went down.
1824 // Send key cancellation but do not consume the touch yet.
1825 // This is useful when the user swipes through from the virtual key area
1826 // into the main display surface.
1827 mCurrentVirtualKey.down = false;
1828 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001829 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1830 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001831 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1832 AKEY_EVENT_FLAG_FROM_SYSTEM |
1833 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1834 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001835 }
1836 }
1837
1838 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1839 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1840 // Pointer just went down. Check for virtual key press or off-screen touches.
1841 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1842 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001843 // Skip checking whether the pointer is inside the physical frame if the device is in
1844 // unscaled mode.
1845 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1846 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001847 // If exactly one pointer went down, check for virtual key hit.
1848 // Otherwise we will drop the entire stroke.
1849 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1850 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1851 if (virtualKey) {
1852 mCurrentVirtualKey.down = true;
1853 mCurrentVirtualKey.downTime = when;
1854 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1855 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1856 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001857 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1858 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001859
1860 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001861 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1862 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1863 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001864 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1865 AKEY_EVENT_ACTION_DOWN,
1866 AKEY_EVENT_FLAG_FROM_SYSTEM |
1867 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001868 }
1869 }
1870 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001871 outConsumed = true;
1872 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001873 }
1874 }
1875
1876 // Disable all virtual key touches that happen within a short time interval of the
1877 // most recent touch within the screen area. The idea is to filter out stray
1878 // virtual key presses when interacting with the touch screen.
1879 //
1880 // Problems we're trying to solve:
1881 //
1882 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1883 // virtual key area that is implemented by a separate touch panel and accidentally
1884 // triggers a virtual key.
1885 //
1886 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1887 // area and accidentally triggers a virtual key. This often happens when virtual keys
1888 // are layed out below the screen near to where the on screen keyboard's space bar
1889 // is displayed.
1890 if (mConfig.virtualKeyQuietTime > 0 &&
1891 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001892 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001893 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001894 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001895}
1896
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001897NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1898 uint32_t policyFlags, int32_t keyEventAction,
1899 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001900 int32_t keyCode = mCurrentVirtualKey.keyCode;
1901 int32_t scanCode = mCurrentVirtualKey.scanCode;
1902 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001903 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001904 policyFlags |= POLICY_FLAG_VIRTUAL;
1905
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001906 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1907 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1908 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001909}
1910
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001911std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1912 uint32_t policyFlags) {
1913 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001914 if (mCurrentMotionAborted) {
1915 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001916 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001917 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001918 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1919 if (!currentIdBits.isEmpty()) {
1920 int32_t metaState = getContext()->getGlobalMetaState();
1921 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001922 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001923 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1924 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001925 mCurrentCookedState.cookedPointerData.pointerProperties,
1926 mCurrentCookedState.cookedPointerData.pointerCoords,
1927 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1928 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1929 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001930 mCurrentMotionAborted = true;
1931 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001932 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001933}
1934
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001935// Updates pointer coords and properties for pointers with specified ids that have moved.
1936// Returns true if any of them changed.
1937static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1938 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1939 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1940 BitSet32 idBits) {
1941 bool changed = false;
1942 while (!idBits.isEmpty()) {
1943 uint32_t id = idBits.clearFirstMarkedBit();
1944 uint32_t inIndex = inIdToIndex[id];
1945 uint32_t outIndex = outIdToIndex[id];
1946
1947 const PointerProperties& curInProperties = inProperties[inIndex];
1948 const PointerCoords& curInCoords = inCoords[inIndex];
1949 PointerProperties& curOutProperties = outProperties[outIndex];
1950 PointerCoords& curOutCoords = outCoords[outIndex];
1951
1952 if (curInProperties != curOutProperties) {
1953 curOutProperties.copyFrom(curInProperties);
1954 changed = true;
1955 }
1956
1957 if (curInCoords != curOutCoords) {
1958 curOutCoords.copyFrom(curInCoords);
1959 changed = true;
1960 }
1961 }
1962 return changed;
1963}
1964
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001965std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1966 uint32_t policyFlags) {
1967 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001968 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1969 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1970 int32_t metaState = getContext()->getGlobalMetaState();
1971 int32_t buttonState = mCurrentCookedState.buttonState;
1972
1973 if (currentIdBits == lastIdBits) {
1974 if (!currentIdBits.isEmpty()) {
1975 // No pointer id changes so this is a move event.
1976 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001977 out.push_back(
1978 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1979 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1980 mCurrentCookedState.cookedPointerData.pointerProperties,
1981 mCurrentCookedState.cookedPointerData.pointerCoords,
1982 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1983 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1984 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001985 }
1986 } else {
1987 // There may be pointers going up and pointers going down and pointers moving
1988 // all at the same time.
1989 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1990 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1991 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1992 BitSet32 dispatchedIdBits(lastIdBits.value);
1993
1994 // Update last coordinates of pointers that have moved so that we observe the new
1995 // pointer positions at the same time as other pointers that have just gone up.
1996 bool moveNeeded =
1997 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1998 mCurrentCookedState.cookedPointerData.pointerCoords,
1999 mCurrentCookedState.cookedPointerData.idToIndex,
2000 mLastCookedState.cookedPointerData.pointerProperties,
2001 mLastCookedState.cookedPointerData.pointerCoords,
2002 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2003 if (buttonState != mLastCookedState.buttonState) {
2004 moveNeeded = true;
2005 }
2006
2007 // Dispatch pointer up events.
2008 while (!upIdBits.isEmpty()) {
2009 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002010 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002011 if (isCanceled) {
2012 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2013 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002014 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2015 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2016 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2017 buttonState, 0,
2018 mLastCookedState.cookedPointerData.pointerProperties,
2019 mLastCookedState.cookedPointerData.pointerCoords,
2020 mLastCookedState.cookedPointerData.idToIndex,
2021 dispatchedIdBits, upId, mOrientedXPrecision,
2022 mOrientedYPrecision, mDownTime,
2023 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002024 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002025 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002026 }
2027
2028 // Dispatch move events if any of the remaining pointers moved from their old locations.
2029 // Although applications receive new locations as part of individual pointer up
2030 // events, they do not generally handle them except when presented in a move event.
2031 if (moveNeeded && !moveIdBits.isEmpty()) {
2032 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002033 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2034 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2035 mCurrentCookedState.cookedPointerData.pointerProperties,
2036 mCurrentCookedState.cookedPointerData.pointerCoords,
2037 mCurrentCookedState.cookedPointerData.idToIndex,
2038 dispatchedIdBits, -1, mOrientedXPrecision,
2039 mOrientedYPrecision, mDownTime,
2040 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002041 }
2042
2043 // Dispatch pointer down events using the new pointer locations.
2044 while (!downIdBits.isEmpty()) {
2045 uint32_t downId = downIdBits.clearFirstMarkedBit();
2046 dispatchedIdBits.markBit(downId);
2047
2048 if (dispatchedIdBits.count() == 1) {
2049 // First pointer is going down. Set down time.
2050 mDownTime = when;
2051 }
2052
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002053 out.push_back(
2054 dispatchMotion(when, readTime, policyFlags, mSource,
2055 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2056 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2057 mCurrentCookedState.cookedPointerData.pointerCoords,
2058 mCurrentCookedState.cookedPointerData.idToIndex,
2059 dispatchedIdBits, downId, mOrientedXPrecision,
2060 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002061 }
2062 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002063 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002064}
2065
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002066std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2067 uint32_t policyFlags) {
2068 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002069 if (mSentHoverEnter &&
2070 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2071 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2072 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002073 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2074 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2075 mLastCookedState.buttonState, 0,
2076 mLastCookedState.cookedPointerData.pointerProperties,
2077 mLastCookedState.cookedPointerData.pointerCoords,
2078 mLastCookedState.cookedPointerData.idToIndex,
2079 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2080 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2081 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002082 mSentHoverEnter = false;
2083 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002084 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002085}
2086
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002087std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2088 uint32_t policyFlags) {
2089 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002090 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2091 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2092 int32_t metaState = getContext()->getGlobalMetaState();
2093 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002094 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2095 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2096 mCurrentRawState.buttonState, 0,
2097 mCurrentCookedState.cookedPointerData.pointerProperties,
2098 mCurrentCookedState.cookedPointerData.pointerCoords,
2099 mCurrentCookedState.cookedPointerData.idToIndex,
2100 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2101 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2102 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002103 mSentHoverEnter = true;
2104 }
2105
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002106 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2107 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2108 mCurrentRawState.buttonState, 0,
2109 mCurrentCookedState.cookedPointerData.pointerProperties,
2110 mCurrentCookedState.cookedPointerData.pointerCoords,
2111 mCurrentCookedState.cookedPointerData.idToIndex,
2112 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2113 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2114 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002115 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002116 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002117}
2118
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002119std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2120 uint32_t policyFlags) {
2121 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002122 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2123 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2124 const int32_t metaState = getContext()->getGlobalMetaState();
2125 int32_t buttonState = mLastCookedState.buttonState;
2126 while (!releasedButtons.isEmpty()) {
2127 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2128 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002129 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2130 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2131 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002132 mLastCookedState.cookedPointerData.pointerProperties,
2133 mLastCookedState.cookedPointerData.pointerCoords,
2134 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002135 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2136 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002137 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002138 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002139}
2140
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002141std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2142 uint32_t policyFlags) {
2143 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002144 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2145 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2146 const int32_t metaState = getContext()->getGlobalMetaState();
2147 int32_t buttonState = mLastCookedState.buttonState;
2148 while (!pressedButtons.isEmpty()) {
2149 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2150 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002151 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2152 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2153 buttonState, 0,
2154 mCurrentCookedState.cookedPointerData.pointerProperties,
2155 mCurrentCookedState.cookedPointerData.pointerCoords,
2156 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2157 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2158 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002159 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002160 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002161}
2162
LiZhihong758eb562022-11-03 15:28:29 +08002163std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2164 uint32_t policyFlags,
2165 BitSet32 idBits,
2166 nsecs_t readTime) {
2167 std::list<NotifyArgs> out;
2168 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2169 const int32_t metaState = getContext()->getGlobalMetaState();
2170 int32_t buttonState = mLastCookedState.buttonState;
2171
2172 while (!releasedButtons.isEmpty()) {
2173 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2174 buttonState &= ~actionButton;
2175 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2176 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2177 metaState, buttonState, 0,
2178 mPointerGesture.lastGestureProperties,
2179 mPointerGesture.lastGestureCoords,
2180 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2181 mOrientedXPrecision, mOrientedYPrecision,
2182 mPointerGesture.downTime, MotionClassification::NONE));
2183 }
2184 return out;
2185}
2186
2187std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2188 uint32_t policyFlags,
2189 BitSet32 idBits,
2190 nsecs_t readTime) {
2191 std::list<NotifyArgs> out;
2192 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2193 const int32_t metaState = getContext()->getGlobalMetaState();
2194 int32_t buttonState = mLastCookedState.buttonState;
2195
2196 while (!pressedButtons.isEmpty()) {
2197 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2198 buttonState |= actionButton;
2199 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2200 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2201 buttonState, 0, mPointerGesture.currentGestureProperties,
2202 mPointerGesture.currentGestureCoords,
2203 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2204 mOrientedXPrecision, mOrientedYPrecision,
2205 mPointerGesture.downTime, MotionClassification::NONE));
2206 }
2207 return out;
2208}
2209
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002210const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2211 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2212 return cookedPointerData.touchingIdBits;
2213 }
2214 return cookedPointerData.hoveringIdBits;
2215}
2216
2217void TouchInputMapper::cookPointerData() {
2218 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2219
2220 mCurrentCookedState.cookedPointerData.clear();
2221 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2222 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2223 mCurrentRawState.rawPointerData.hoveringIdBits;
2224 mCurrentCookedState.cookedPointerData.touchingIdBits =
2225 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002226 mCurrentCookedState.cookedPointerData.canceledIdBits =
2227 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002228
2229 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2230 mCurrentCookedState.buttonState = 0;
2231 } else {
2232 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2233 }
2234
2235 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002236 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002237 for (uint32_t i = 0; i < currentPointerCount; i++) {
2238 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2239
2240 // Size
2241 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2242 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002243 case Calibration::SizeCalibration::GEOMETRIC:
2244 case Calibration::SizeCalibration::DIAMETER:
2245 case Calibration::SizeCalibration::BOX:
2246 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002247 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2248 touchMajor = in.touchMajor;
2249 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2250 toolMajor = in.toolMajor;
2251 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2252 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2253 : in.touchMajor;
2254 } else if (mRawPointerAxes.touchMajor.valid) {
2255 toolMajor = touchMajor = in.touchMajor;
2256 toolMinor = touchMinor =
2257 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2258 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2259 : in.touchMajor;
2260 } else if (mRawPointerAxes.toolMajor.valid) {
2261 touchMajor = toolMajor = in.toolMajor;
2262 touchMinor = toolMinor =
2263 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2264 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2265 : in.toolMajor;
2266 } else {
2267 ALOG_ASSERT(false,
2268 "No touch or tool axes. "
2269 "Size calibration should have been resolved to NONE.");
2270 touchMajor = 0;
2271 touchMinor = 0;
2272 toolMajor = 0;
2273 toolMinor = 0;
2274 size = 0;
2275 }
2276
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002277 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002278 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2279 if (touchingCount > 1) {
2280 touchMajor /= touchingCount;
2281 touchMinor /= touchingCount;
2282 toolMajor /= touchingCount;
2283 toolMinor /= touchingCount;
2284 size /= touchingCount;
2285 }
2286 }
2287
Michael Wright227c5542020-07-02 18:30:52 +01002288 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002289 touchMajor *= mGeometricScale;
2290 touchMinor *= mGeometricScale;
2291 toolMajor *= mGeometricScale;
2292 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002293 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002294 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2295 touchMinor = touchMajor;
2296 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2297 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002298 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002299 touchMinor = touchMajor;
2300 toolMinor = toolMajor;
2301 }
2302
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002303 mCalibration.applySizeScaleAndBias(touchMajor);
2304 mCalibration.applySizeScaleAndBias(touchMinor);
2305 mCalibration.applySizeScaleAndBias(toolMajor);
2306 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002307 size *= mSizeScale;
2308 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002309 case Calibration::SizeCalibration::DEFAULT:
2310 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2311 break;
2312 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002313 touchMajor = 0;
2314 touchMinor = 0;
2315 toolMajor = 0;
2316 toolMinor = 0;
2317 size = 0;
2318 break;
2319 }
2320
2321 // Pressure
2322 float pressure;
2323 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002324 case Calibration::PressureCalibration::PHYSICAL:
2325 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002326 pressure = in.pressure * mPressureScale;
2327 break;
2328 default:
2329 pressure = in.isHovering ? 0 : 1;
2330 break;
2331 }
2332
2333 // Tilt and Orientation
2334 float tilt;
2335 float orientation;
2336 if (mHaveTilt) {
2337 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2338 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002339 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002340 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2341 } else {
2342 tilt = 0;
2343
2344 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002345 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002346 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002347 break;
Michael Wright227c5542020-07-02 18:30:52 +01002348 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002349 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2350 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2351 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002352 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002353 float confidence = hypotf(c1, c2);
2354 float scale = 1.0f + confidence / 16.0f;
2355 touchMajor *= scale;
2356 touchMinor /= scale;
2357 toolMajor *= scale;
2358 toolMinor /= scale;
2359 } else {
2360 orientation = 0;
2361 }
2362 break;
2363 }
2364 default:
2365 orientation = 0;
2366 }
2367 }
2368
2369 // Distance
2370 float distance;
2371 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002372 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002373 distance = in.distance * mDistanceScale;
2374 break;
2375 default:
2376 distance = 0;
2377 }
2378
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002379 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2380 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002381 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2382 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002383
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002384 // Write output coords.
2385 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2386 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002387 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2388 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002389 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2390 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2391 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2392 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2393 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2394 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2395 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002396 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2397 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002398
Chris Ye364fdb52020-08-05 15:07:56 -07002399 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002400 uint32_t id = in.id;
2401 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2402 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2403 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002404 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2405 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002406 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2407 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2408 }
2409
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002410 // Write output properties.
2411 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002412 properties.clear();
2413 properties.id = id;
2414 properties.toolType = in.toolType;
2415
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002416 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002417 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002418 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002419 }
2420}
2421
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002422std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2423 uint32_t policyFlags,
2424 PointerUsage pointerUsage) {
2425 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002426 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002427 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002428 mPointerUsage = pointerUsage;
2429 }
2430
2431 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002432 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002433 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002434 break;
Michael Wright227c5542020-07-02 18:30:52 +01002435 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002436 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002437 break;
Michael Wright227c5542020-07-02 18:30:52 +01002438 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002439 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002440 break;
Michael Wright227c5542020-07-02 18:30:52 +01002441 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002442 break;
2443 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002444 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002445}
2446
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002447std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2448 uint32_t policyFlags) {
2449 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002450 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002451 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002452 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002453 break;
Michael Wright227c5542020-07-02 18:30:52 +01002454 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002455 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002456 break;
Michael Wright227c5542020-07-02 18:30:52 +01002457 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002458 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002459 break;
Michael Wright227c5542020-07-02 18:30:52 +01002460 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002461 break;
2462 }
2463
Michael Wright227c5542020-07-02 18:30:52 +01002464 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002465 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002466}
2467
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002468std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2469 uint32_t policyFlags,
2470 bool isTimeout) {
2471 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002472 // Update current gesture coordinates.
2473 bool cancelPreviousGesture, finishPreviousGesture;
2474 bool sendEvents =
2475 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2476 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002477 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002478 }
2479 if (finishPreviousGesture) {
2480 cancelPreviousGesture = false;
2481 }
2482
2483 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002484 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002485 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002486 if (finishPreviousGesture || cancelPreviousGesture) {
2487 mPointerController->clearSpots();
2488 }
2489
Michael Wright227c5542020-07-02 18:30:52 +01002490 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002491 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2492 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002493 mPointerGesture.currentGestureIdBits,
2494 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002495 }
2496 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002497 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002498 }
2499
2500 // Show or hide the pointer if needed.
2501 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002502 case PointerGesture::Mode::NEUTRAL:
2503 case PointerGesture::Mode::QUIET:
2504 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2505 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002506 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002507 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002508 }
2509 break;
Michael Wright227c5542020-07-02 18:30:52 +01002510 case PointerGesture::Mode::TAP:
2511 case PointerGesture::Mode::TAP_DRAG:
2512 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2513 case PointerGesture::Mode::HOVER:
2514 case PointerGesture::Mode::PRESS:
2515 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002516 // Unfade the pointer when the current gesture manipulates the
2517 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002518 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002519 break;
Michael Wright227c5542020-07-02 18:30:52 +01002520 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002521 // Fade the pointer when the current gesture manipulates a different
2522 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002523 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002524 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002525 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002526 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002527 }
2528 break;
2529 }
2530
2531 // Send events!
2532 int32_t metaState = getContext()->getGlobalMetaState();
2533 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002534 const MotionClassification classification =
2535 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2536 ? MotionClassification::TWO_FINGER_SWIPE
2537 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002538
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002539 uint32_t flags = 0;
2540
2541 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2542 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2543 }
2544
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002545 // Update last coordinates of pointers that have moved so that we observe the new
2546 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002547 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2548 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2549 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2550 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2551 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2552 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002553 bool moveNeeded = false;
2554 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2555 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2556 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2557 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2558 mPointerGesture.lastGestureIdBits.value);
2559 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2560 mPointerGesture.currentGestureCoords,
2561 mPointerGesture.currentGestureIdToIndex,
2562 mPointerGesture.lastGestureProperties,
2563 mPointerGesture.lastGestureCoords,
2564 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2565 if (buttonState != mLastCookedState.buttonState) {
2566 moveNeeded = true;
2567 }
2568 }
2569
2570 // Send motion events for all pointers that went up or were canceled.
2571 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2572 if (!dispatchedGestureIdBits.isEmpty()) {
2573 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002574 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002575 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002576 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002577 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2578 mPointerGesture.lastGestureProperties,
2579 mPointerGesture.lastGestureCoords,
2580 mPointerGesture.lastGestureIdToIndex,
2581 dispatchedGestureIdBits, -1, 0, 0,
2582 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002583
2584 dispatchedGestureIdBits.clear();
2585 } else {
2586 BitSet32 upGestureIdBits;
2587 if (finishPreviousGesture) {
2588 upGestureIdBits = dispatchedGestureIdBits;
2589 } else {
2590 upGestureIdBits.value =
2591 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2592 }
2593 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002594 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2595 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2596 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2597 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2598 readTime);
2599 }
2600 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002601 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2602 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2603 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2604 mPointerGesture.lastGestureProperties,
2605 mPointerGesture.lastGestureCoords,
2606 mPointerGesture.lastGestureIdToIndex,
2607 dispatchedGestureIdBits, id, 0, 0,
2608 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002609
2610 dispatchedGestureIdBits.clearBit(id);
2611 }
2612 }
2613 }
2614
2615 // Send motion events for all pointers that moved.
2616 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002617 out.push_back(
2618 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2619 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2620 mPointerGesture.currentGestureProperties,
2621 mPointerGesture.currentGestureCoords,
2622 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2623 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002624 }
2625
2626 // Send motion events for all pointers that went down.
2627 if (down) {
2628 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2629 ~dispatchedGestureIdBits.value);
2630 while (!downGestureIdBits.isEmpty()) {
2631 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2632 dispatchedGestureIdBits.markBit(id);
2633
2634 if (dispatchedGestureIdBits.count() == 1) {
2635 mPointerGesture.downTime = when;
2636 }
2637
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002638 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2639 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2640 buttonState, 0, mPointerGesture.currentGestureProperties,
2641 mPointerGesture.currentGestureCoords,
2642 mPointerGesture.currentGestureIdToIndex,
2643 dispatchedGestureIdBits, id, 0, 0,
2644 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002645 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2646 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2647 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2648 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2649 readTime);
2650 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002651 }
2652 }
2653
2654 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002655 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002656 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2657 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2658 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2659 mPointerGesture.currentGestureProperties,
2660 mPointerGesture.currentGestureCoords,
2661 mPointerGesture.currentGestureIdToIndex,
2662 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2663 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002664 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2665 // Synthesize a hover move event after all pointers go up to indicate that
2666 // the pointer is hovering again even if the user is not currently touching
2667 // the touch pad. This ensures that a view will receive a fresh hover enter
2668 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002669 float x, y;
2670 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002671
2672 PointerProperties pointerProperties;
2673 pointerProperties.clear();
2674 pointerProperties.id = 0;
2675 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2676
2677 PointerCoords pointerCoords;
2678 pointerCoords.clear();
2679 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2680 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2681
2682 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002683 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2684 mSource, displayId, policyFlags,
2685 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2686 buttonState, MotionClassification::NONE,
2687 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2688 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2689 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002690 }
2691
2692 // Update state.
2693 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2694 if (!down) {
2695 mPointerGesture.lastGestureIdBits.clear();
2696 } else {
2697 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2698 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2699 uint32_t id = idBits.clearFirstMarkedBit();
2700 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2701 mPointerGesture.lastGestureProperties[index].copyFrom(
2702 mPointerGesture.currentGestureProperties[index]);
2703 mPointerGesture.lastGestureCoords[index].copyFrom(
2704 mPointerGesture.currentGestureCoords[index]);
2705 mPointerGesture.lastGestureIdToIndex[id] = index;
2706 }
2707 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002708 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002709}
2710
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002711std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2712 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002713 const MotionClassification classification =
2714 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2715 ? MotionClassification::TWO_FINGER_SWIPE
2716 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002717 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002718 // Cancel previously dispatches pointers.
2719 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2720 int32_t metaState = getContext()->getGlobalMetaState();
2721 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002722 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002723 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2724 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002725 mPointerGesture.lastGestureProperties,
2726 mPointerGesture.lastGestureCoords,
2727 mPointerGesture.lastGestureIdToIndex,
2728 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2729 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002730 }
2731
2732 // Reset the current pointer gesture.
2733 mPointerGesture.reset();
2734 mPointerVelocityControl.reset();
2735
2736 // Remove any current spots.
2737 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002738 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002739 mPointerController->clearSpots();
2740 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002741 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002742}
2743
2744bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2745 bool* outFinishPreviousGesture, bool isTimeout) {
2746 *outCancelPreviousGesture = false;
2747 *outFinishPreviousGesture = false;
2748
2749 // Handle TAP timeout.
2750 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002751 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002752
Michael Wright227c5542020-07-02 18:30:52 +01002753 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002754 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2755 // The tap/drag timeout has not yet expired.
2756 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2757 mConfig.pointerGestureTapDragInterval);
2758 } else {
2759 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002760 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002761 *outFinishPreviousGesture = true;
2762
2763 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002764 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002765 mPointerGesture.currentGestureIdBits.clear();
2766
2767 mPointerVelocityControl.reset();
2768 return true;
2769 }
2770 }
2771
2772 // We did not handle this timeout.
2773 return false;
2774 }
2775
2776 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2777 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2778
2779 // Update the velocity tracker.
2780 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002781 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002782 uint32_t id = idBits.clearFirstMarkedBit();
2783 const RawPointerData::Pointer& pointer =
2784 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002785 const float x = pointer.x * mPointerXMovementScale;
2786 const float y = pointer.y * mPointerYMovementScale;
2787 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2788 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002789 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002790 }
2791
2792 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2793 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002794 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2795 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2796 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002797 mPointerGesture.resetTap();
2798 }
2799
2800 // Pick a new active touch id if needed.
2801 // Choose an arbitrary pointer that just went down, if there is one.
2802 // Otherwise choose an arbitrary remaining pointer.
2803 // This guarantees we always have an active touch id when there is at least one pointer.
2804 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002805 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002806 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002807 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002808 mPointerGesture.firstTouchTime = when;
2809 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002810 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2811 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2812 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2813 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002814 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002815 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002816
2817 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002818 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002819 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002820 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2821 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2822 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002823 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002824 *outFinishPreviousGesture = true;
2825 }
2826
2827 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002828 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002829 mPointerGesture.currentGestureIdBits.clear();
2830
2831 mPointerVelocityControl.reset();
2832 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2833 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2834 // The pointer follows the active touch point.
2835 // Emit DOWN, MOVE, UP events at the pointer location.
2836 //
2837 // Only the active touch matters; other fingers are ignored. This policy helps
2838 // to handle the case where the user places a second finger on the touch pad
2839 // to apply the necessary force to depress an integrated button below the surface.
2840 // We don't want the second finger to be delivered to applications.
2841 //
2842 // For this to work well, we need to make sure to track the pointer that is really
2843 // active. If the user first puts one finger down to click then adds another
2844 // finger to drag then the active pointer should switch to the finger that is
2845 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002846 ALOGD_IF(DEBUG_GESTURES,
2847 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2848 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002849 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002850 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002851 *outFinishPreviousGesture = true;
2852 mPointerGesture.activeGestureId = 0;
2853 }
2854
2855 // Switch pointers if needed.
2856 // Find the fastest pointer and follow it.
2857 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002858 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002859 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002860 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002861 ALOGD_IF(DEBUG_GESTURES,
2862 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2863 "bestSpeed=%0.3f",
2864 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002865 }
2866 }
2867
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002868 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002869 // When using spots, the click will occur at the position of the anchor
2870 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002871 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002872 } else {
2873 mPointerVelocityControl.reset();
2874 }
2875
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002876 float x, y;
2877 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002878
Michael Wright227c5542020-07-02 18:30:52 +01002879 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002880 mPointerGesture.currentGestureIdBits.clear();
2881 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2882 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2883 mPointerGesture.currentGestureProperties[0].clear();
2884 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2885 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2886 mPointerGesture.currentGestureCoords[0].clear();
2887 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2888 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2889 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2890 } else if (currentFingerCount == 0) {
2891 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002892 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002893 *outFinishPreviousGesture = true;
2894 }
2895
2896 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2897 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2898 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002899 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2900 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002901 lastFingerCount == 1) {
2902 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002903 float x, y;
2904 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002905 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2906 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002907 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002908
2909 mPointerGesture.tapUpTime = when;
2910 getContext()->requestTimeoutAtTime(when +
2911 mConfig.pointerGestureTapDragInterval);
2912
2913 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002914 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002915 mPointerGesture.currentGestureIdBits.clear();
2916 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2917 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2918 mPointerGesture.currentGestureProperties[0].clear();
2919 mPointerGesture.currentGestureProperties[0].id =
2920 mPointerGesture.activeGestureId;
2921 mPointerGesture.currentGestureProperties[0].toolType =
2922 AMOTION_EVENT_TOOL_TYPE_FINGER;
2923 mPointerGesture.currentGestureCoords[0].clear();
2924 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2925 mPointerGesture.tapX);
2926 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2927 mPointerGesture.tapY);
2928 mPointerGesture.currentGestureCoords[0]
2929 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2930
2931 tapped = true;
2932 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002933 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2934 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002935 }
2936 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002937 if (DEBUG_GESTURES) {
2938 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2939 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2940 (when - mPointerGesture.tapDownTime) * 0.000001f);
2941 } else {
2942 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2943 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002944 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002945 }
2946 }
2947
2948 mPointerVelocityControl.reset();
2949
2950 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002951 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002952 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002953 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002954 mPointerGesture.currentGestureIdBits.clear();
2955 }
2956 } else if (currentFingerCount == 1) {
2957 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2958 // The pointer follows the active touch point.
2959 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2960 // When in TAP_DRAG, emit MOVE events at the pointer location.
2961 ALOG_ASSERT(activeTouchId >= 0);
2962
Michael Wright227c5542020-07-02 18:30:52 +01002963 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2964 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002965 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002966 float x, y;
2967 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002968 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2969 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002970 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002971 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002972 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2973 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002974 }
2975 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002976 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2977 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002978 }
Michael Wright227c5542020-07-02 18:30:52 +01002979 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2980 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002981 }
2982
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002983 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002984 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002985 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002986 } else {
2987 mPointerVelocityControl.reset();
2988 }
2989
2990 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002991 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00002992 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002993 down = true;
2994 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002995 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01002996 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002997 *outFinishPreviousGesture = true;
2998 }
2999 mPointerGesture.activeGestureId = 0;
3000 down = false;
3001 }
3002
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003003 float x, y;
3004 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003005
3006 mPointerGesture.currentGestureIdBits.clear();
3007 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3008 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3009 mPointerGesture.currentGestureProperties[0].clear();
3010 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3011 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3012 mPointerGesture.currentGestureCoords[0].clear();
3013 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3014 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3015 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3016 down ? 1.0f : 0.0f);
3017
3018 if (lastFingerCount == 0 && currentFingerCount != 0) {
3019 mPointerGesture.resetTap();
3020 mPointerGesture.tapDownTime = when;
3021 mPointerGesture.tapX = x;
3022 mPointerGesture.tapY = y;
3023 }
3024 } else {
3025 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003026 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003027 }
3028
3029 mPointerController->setButtonState(mCurrentRawState.buttonState);
3030
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003031 if (DEBUG_GESTURES) {
3032 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3033 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3034 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3035 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3036 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3037 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3038 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3039 uint32_t id = idBits.clearFirstMarkedBit();
3040 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3041 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3042 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3043 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3044 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3045 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3046 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3047 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3048 }
3049 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3050 uint32_t id = idBits.clearFirstMarkedBit();
3051 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3052 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3053 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3054 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3055 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3056 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3057 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3058 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3059 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003060 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003061 return true;
3062}
3063
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003064bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3065 if (mPointerGesture.activeTouchId < 0) {
3066 mPointerGesture.resetQuietTime();
3067 return false;
3068 }
3069
3070 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3071 return true;
3072 }
3073
3074 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3075 bool isQuietTime = false;
3076 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3077 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3078 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3079 currentFingerCount < 2) {
3080 // Enter quiet time when exiting swipe or freeform state.
3081 // This is to prevent accidentally entering the hover state and flinging the
3082 // pointer when finishing a swipe and there is still one pointer left onscreen.
3083 isQuietTime = true;
3084 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3085 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3086 // Enter quiet time when releasing the button and there are still two or more
3087 // fingers down. This may indicate that one finger was used to press the button
3088 // but it has not gone up yet.
3089 isQuietTime = true;
3090 }
3091 if (isQuietTime) {
3092 mPointerGesture.quietTime = when;
3093 }
3094 return isQuietTime;
3095}
3096
3097std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3098 int32_t bestId = -1;
3099 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3100 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3101 uint32_t id = idBits.clearFirstMarkedBit();
3102 std::optional<float> vx =
3103 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3104 std::optional<float> vy =
3105 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3106 if (vx && vy) {
3107 float speed = hypotf(*vx, *vy);
3108 if (speed > bestSpeed) {
3109 bestId = id;
3110 bestSpeed = speed;
3111 }
3112 }
3113 }
3114 return std::make_pair(bestId, bestSpeed);
3115}
3116
3117void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3118 bool* finishPreviousGesture) {
3119 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3120 // to move before deciding what to do.
3121 //
3122 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3123 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3124 // just a press or long-press at the pointer location.
3125 //
3126 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3127 // pointer location.
3128 //
3129 // When the two fingers move enough or when additional fingers are added, we make a decision to
3130 // transition into SWIPE or FREEFORM mode accordingly.
3131 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3132 ALOG_ASSERT(activeTouchId >= 0);
3133
3134 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3135 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3136 bool settled =
3137 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3138 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3139 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3140 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3141 *finishPreviousGesture = true;
3142 } else if (!settled && currentFingerCount > lastFingerCount) {
3143 // Additional pointers have gone down but not yet settled.
3144 // Reset the gesture.
3145 ALOGD_IF(DEBUG_GESTURES,
3146 "Gestures: Resetting gesture since additional pointers went down for "
3147 "MULTITOUCH, settle time remaining %0.3fms",
3148 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3149 when) * 0.000001f);
3150 *cancelPreviousGesture = true;
3151 } else {
3152 // Continue previous gesture.
3153 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3154 }
3155
3156 if (*finishPreviousGesture || *cancelPreviousGesture) {
3157 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3158 mPointerGesture.activeGestureId = 0;
3159 mPointerGesture.referenceIdBits.clear();
3160 mPointerVelocityControl.reset();
3161
3162 // Use the centroid and pointer location as the reference points for the gesture.
3163 ALOGD_IF(DEBUG_GESTURES,
3164 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3165 "%0.3fms",
3166 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3167 when) * 0.000001f);
3168 mCurrentRawState.rawPointerData
3169 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3170 &mPointerGesture.referenceTouchY);
3171 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3172 &mPointerGesture.referenceGestureY);
3173 }
3174
3175 // Clear the reference deltas for fingers not yet included in the reference calculation.
3176 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3177 ~mPointerGesture.referenceIdBits.value);
3178 !idBits.isEmpty();) {
3179 uint32_t id = idBits.clearFirstMarkedBit();
3180 mPointerGesture.referenceDeltas[id].dx = 0;
3181 mPointerGesture.referenceDeltas[id].dy = 0;
3182 }
3183 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3184
3185 // Add delta for all fingers and calculate a common movement delta.
3186 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3187 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3188 mCurrentCookedState.fingerIdBits.value);
3189 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3190 bool first = (idBits == commonIdBits);
3191 uint32_t id = idBits.clearFirstMarkedBit();
3192 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3193 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3194 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3195 delta.dx += cpd.x - lpd.x;
3196 delta.dy += cpd.y - lpd.y;
3197
3198 if (first) {
3199 commonDeltaRawX = delta.dx;
3200 commonDeltaRawY = delta.dy;
3201 } else {
3202 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3203 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3204 }
3205 }
3206
3207 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3208 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3209 float dist[MAX_POINTER_ID + 1];
3210 int32_t distOverThreshold = 0;
3211 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3212 uint32_t id = idBits.clearFirstMarkedBit();
3213 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3214 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3215 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3216 distOverThreshold += 1;
3217 }
3218 }
3219
3220 // Only transition when at least two pointers have moved further than
3221 // the minimum distance threshold.
3222 if (distOverThreshold >= 2) {
3223 if (currentFingerCount > 2) {
3224 // There are more than two pointers, switch to FREEFORM.
3225 ALOGD_IF(DEBUG_GESTURES,
3226 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3227 currentFingerCount);
3228 *cancelPreviousGesture = true;
3229 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3230 } else {
3231 // There are exactly two pointers.
3232 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3233 uint32_t id1 = idBits.clearFirstMarkedBit();
3234 uint32_t id2 = idBits.firstMarkedBit();
3235 const RawPointerData::Pointer& p1 =
3236 mCurrentRawState.rawPointerData.pointerForId(id1);
3237 const RawPointerData::Pointer& p2 =
3238 mCurrentRawState.rawPointerData.pointerForId(id2);
3239 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3240 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3241 // There are two pointers but they are too far apart for a SWIPE,
3242 // switch to FREEFORM.
3243 ALOGD_IF(DEBUG_GESTURES,
3244 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3245 mutualDistance, mPointerGestureMaxSwipeWidth);
3246 *cancelPreviousGesture = true;
3247 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3248 } else {
3249 // There are two pointers. Wait for both pointers to start moving
3250 // before deciding whether this is a SWIPE or FREEFORM gesture.
3251 float dist1 = dist[id1];
3252 float dist2 = dist[id2];
3253 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3254 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3255 // Calculate the dot product of the displacement vectors.
3256 // When the vectors are oriented in approximately the same direction,
3257 // the angle betweeen them is near zero and the cosine of the angle
3258 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3259 // mag(v2).
3260 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3261 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3262 float dx1 = delta1.dx * mPointerXZoomScale;
3263 float dy1 = delta1.dy * mPointerYZoomScale;
3264 float dx2 = delta2.dx * mPointerXZoomScale;
3265 float dy2 = delta2.dy * mPointerYZoomScale;
3266 float dot = dx1 * dx2 + dy1 * dy2;
3267 float cosine = dot / (dist1 * dist2); // denominator always > 0
3268 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3269 // Pointers are moving in the same direction. Switch to SWIPE.
3270 ALOGD_IF(DEBUG_GESTURES,
3271 "Gestures: PRESS transitioned to SWIPE, "
3272 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3273 "cosine %0.3f >= %0.3f",
3274 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3275 mConfig.pointerGestureMultitouchMinDistance, cosine,
3276 mConfig.pointerGestureSwipeTransitionAngleCosine);
3277 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3278 } else {
3279 // Pointers are moving in different directions. Switch to FREEFORM.
3280 ALOGD_IF(DEBUG_GESTURES,
3281 "Gestures: PRESS transitioned to FREEFORM, "
3282 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3283 "cosine %0.3f < %0.3f",
3284 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3285 mConfig.pointerGestureMultitouchMinDistance, cosine,
3286 mConfig.pointerGestureSwipeTransitionAngleCosine);
3287 *cancelPreviousGesture = true;
3288 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3289 }
3290 }
3291 }
3292 }
3293 }
3294 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3295 // Switch from SWIPE to FREEFORM if additional pointers go down.
3296 // Cancel previous gesture.
3297 if (currentFingerCount > 2) {
3298 ALOGD_IF(DEBUG_GESTURES,
3299 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3300 currentFingerCount);
3301 *cancelPreviousGesture = true;
3302 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3303 }
3304 }
3305
3306 // Move the reference points based on the overall group motion of the fingers
3307 // except in PRESS mode while waiting for a transition to occur.
3308 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3309 (commonDeltaRawX || commonDeltaRawY)) {
3310 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3311 uint32_t id = idBits.clearFirstMarkedBit();
3312 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3313 delta.dx = 0;
3314 delta.dy = 0;
3315 }
3316
3317 mPointerGesture.referenceTouchX += commonDeltaRawX;
3318 mPointerGesture.referenceTouchY += commonDeltaRawY;
3319
3320 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3321 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3322
3323 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3324 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3325
3326 mPointerGesture.referenceGestureX += commonDeltaX;
3327 mPointerGesture.referenceGestureY += commonDeltaY;
3328 }
3329
3330 // Report gestures.
3331 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3332 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3333 // PRESS or SWIPE mode.
3334 ALOGD_IF(DEBUG_GESTURES,
3335 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3336 "currentTouchPointerCount=%d",
3337 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3338 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3339
3340 mPointerGesture.currentGestureIdBits.clear();
3341 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3342 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3343 mPointerGesture.currentGestureProperties[0].clear();
3344 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3345 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3346 mPointerGesture.currentGestureCoords[0].clear();
3347 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3348 mPointerGesture.referenceGestureX);
3349 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3350 mPointerGesture.referenceGestureY);
3351 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3352 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3353 float xOffset = static_cast<float>(commonDeltaRawX) /
3354 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3355 float yOffset = static_cast<float>(commonDeltaRawY) /
3356 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3357 mPointerGesture.currentGestureCoords[0]
3358 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3359 mPointerGesture.currentGestureCoords[0]
3360 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3361 }
3362 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3363 // FREEFORM mode.
3364 ALOGD_IF(DEBUG_GESTURES,
3365 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3366 "currentTouchPointerCount=%d",
3367 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3368 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3369
3370 mPointerGesture.currentGestureIdBits.clear();
3371
3372 BitSet32 mappedTouchIdBits;
3373 BitSet32 usedGestureIdBits;
3374 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3375 // Initially, assign the active gesture id to the active touch point
3376 // if there is one. No other touch id bits are mapped yet.
3377 if (!*cancelPreviousGesture) {
3378 mappedTouchIdBits.markBit(activeTouchId);
3379 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3380 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3381 mPointerGesture.activeGestureId;
3382 } else {
3383 mPointerGesture.activeGestureId = -1;
3384 }
3385 } else {
3386 // Otherwise, assume we mapped all touches from the previous frame.
3387 // Reuse all mappings that are still applicable.
3388 mappedTouchIdBits.value =
3389 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3390 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3391
3392 // Check whether we need to choose a new active gesture id because the
3393 // current went went up.
3394 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3395 ~mCurrentCookedState.fingerIdBits.value);
3396 !upTouchIdBits.isEmpty();) {
3397 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3398 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3399 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3400 mPointerGesture.activeGestureId = -1;
3401 break;
3402 }
3403 }
3404 }
3405
3406 ALOGD_IF(DEBUG_GESTURES,
3407 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3408 "activeGestureId=%d",
3409 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3410
3411 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3412 for (uint32_t i = 0; i < currentFingerCount; i++) {
3413 uint32_t touchId = idBits.clearFirstMarkedBit();
3414 uint32_t gestureId;
3415 if (!mappedTouchIdBits.hasBit(touchId)) {
3416 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3417 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3418 ALOGD_IF(DEBUG_GESTURES,
3419 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3420 gestureId);
3421 } else {
3422 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3423 ALOGD_IF(DEBUG_GESTURES,
3424 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3425 touchId, gestureId);
3426 }
3427 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3428 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3429
3430 const RawPointerData::Pointer& pointer =
3431 mCurrentRawState.rawPointerData.pointerForId(touchId);
3432 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3433 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3434 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3435
3436 mPointerGesture.currentGestureProperties[i].clear();
3437 mPointerGesture.currentGestureProperties[i].id = gestureId;
3438 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3439 mPointerGesture.currentGestureCoords[i].clear();
3440 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3441 mPointerGesture.referenceGestureX +
3442 deltaX);
3443 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3444 mPointerGesture.referenceGestureY +
3445 deltaY);
3446 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3447 }
3448
3449 if (mPointerGesture.activeGestureId < 0) {
3450 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3451 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3452 mPointerGesture.activeGestureId);
3453 }
3454 }
3455}
3456
Harry Cutts714d1ad2022-08-24 16:36:43 +00003457void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3458 const RawPointerData::Pointer& currentPointer =
3459 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3460 const RawPointerData::Pointer& lastPointer =
3461 mLastRawState.rawPointerData.pointerForId(pointerId);
3462 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3463 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3464
3465 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3466 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3467
3468 mPointerController->move(deltaX, deltaY);
3469}
3470
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003471std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3472 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003473 mPointerSimple.currentCoords.clear();
3474 mPointerSimple.currentProperties.clear();
3475
3476 bool down, hovering;
3477 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3478 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3479 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003480 mPointerController
3481 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3482 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003483
3484 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3485 down = !hovering;
3486
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003487 float x, y;
3488 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003489 mPointerSimple.currentCoords.copyFrom(
3490 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3491 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3492 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3493 mPointerSimple.currentProperties.id = 0;
3494 mPointerSimple.currentProperties.toolType =
3495 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3496 } else {
3497 down = false;
3498 hovering = false;
3499 }
3500
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003501 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003502}
3503
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003504std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3505 uint32_t policyFlags) {
3506 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003507}
3508
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003509std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3510 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003511 mPointerSimple.currentCoords.clear();
3512 mPointerSimple.currentProperties.clear();
3513
3514 bool down, hovering;
3515 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3516 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003517 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003518 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003519 } else {
3520 mPointerVelocityControl.reset();
3521 }
3522
3523 down = isPointerDown(mCurrentRawState.buttonState);
3524 hovering = !down;
3525
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003526 float x, y;
3527 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003528 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003529 mPointerSimple.currentCoords.copyFrom(
3530 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3531 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3532 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3533 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3534 hovering ? 0.0f : 1.0f);
3535 mPointerSimple.currentProperties.id = 0;
3536 mPointerSimple.currentProperties.toolType =
3537 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3538 } else {
3539 mPointerVelocityControl.reset();
3540
3541 down = false;
3542 hovering = false;
3543 }
3544
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003545 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003546}
3547
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003548std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3549 uint32_t policyFlags) {
3550 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003551
3552 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003553
3554 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003555}
3556
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003557std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3558 uint32_t policyFlags, bool down,
3559 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003560 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3561 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003562 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003563 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003564
3565 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003566 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003567 mPointerController->clearSpots();
3568 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003569 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003570 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003571 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003572 }
Garfield Tan9514d782020-11-10 16:37:23 -08003573 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003574
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003575 float xCursorPosition, yCursorPosition;
3576 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003577
3578 if (mPointerSimple.down && !down) {
3579 mPointerSimple.down = false;
3580
3581 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003582 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3583 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3584 0, metaState, mLastRawState.buttonState,
3585 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3586 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3587 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3588 yCursorPosition, mPointerSimple.downTime,
3589 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003590 }
3591
3592 if (mPointerSimple.hovering && !hovering) {
3593 mPointerSimple.hovering = false;
3594
3595 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003596 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3597 mSource, displayId, policyFlags,
3598 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3599 mLastRawState.buttonState, MotionClassification::NONE,
3600 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3601 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3602 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3603 yCursorPosition, mPointerSimple.downTime,
3604 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003605 }
3606
3607 if (down) {
3608 if (!mPointerSimple.down) {
3609 mPointerSimple.down = true;
3610 mPointerSimple.downTime = when;
3611
3612 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003613 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3614 mSource, displayId, policyFlags,
3615 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3616 mCurrentRawState.buttonState, MotionClassification::NONE,
3617 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3618 &mPointerSimple.currentProperties,
3619 &mPointerSimple.currentCoords, mOrientedXPrecision,
3620 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3621 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003622 }
3623
3624 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003625 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3626 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3627 0, 0, metaState, mCurrentRawState.buttonState,
3628 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3629 &mPointerSimple.currentProperties,
3630 &mPointerSimple.currentCoords, mOrientedXPrecision,
3631 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3632 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003633 }
3634
3635 if (hovering) {
3636 if (!mPointerSimple.hovering) {
3637 mPointerSimple.hovering = true;
3638
3639 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003640 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3641 mSource, displayId, policyFlags,
3642 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3643 mCurrentRawState.buttonState, MotionClassification::NONE,
3644 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3645 &mPointerSimple.currentProperties,
3646 &mPointerSimple.currentCoords, mOrientedXPrecision,
3647 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3648 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003649 }
3650
3651 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003652 out.push_back(
3653 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3654 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3655 metaState, mCurrentRawState.buttonState,
3656 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3657 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3658 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3659 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003660 }
3661
3662 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3663 float vscroll = mCurrentRawState.rawVScroll;
3664 float hscroll = mCurrentRawState.rawHScroll;
3665 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3666 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3667
3668 // Send scroll.
3669 PointerCoords pointerCoords;
3670 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3671 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3672 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3673
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003674 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3675 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3676 0, 0, metaState, mCurrentRawState.buttonState,
3677 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3678 &mPointerSimple.currentProperties, &pointerCoords,
3679 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3680 yCursorPosition, mPointerSimple.downTime,
3681 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003682 }
3683
3684 // Save state.
3685 if (down || hovering) {
3686 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3687 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003688 mPointerSimple.displayId = displayId;
3689 mPointerSimple.source = mSource;
3690 mPointerSimple.lastCursorX = xCursorPosition;
3691 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003692 } else {
3693 mPointerSimple.reset();
3694 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003695 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003696}
3697
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003698std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3699 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003700 std::list<NotifyArgs> out;
3701 if (mPointerSimple.down || mPointerSimple.hovering) {
3702 int32_t metaState = getContext()->getGlobalMetaState();
3703 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3704 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3705 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3706 metaState, mLastRawState.buttonState,
3707 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3708 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3709 mOrientedXPrecision, mOrientedYPrecision,
3710 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3711 mPointerSimple.downTime,
3712 /* videoFrames */ {}));
3713 if (mPointerController != nullptr) {
3714 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3715 }
3716 }
3717 mPointerSimple.reset();
3718 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003719}
3720
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003721static bool isStylusEvent(uint32_t source, int32_t action, const PointerProperties* properties) {
3722 if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
3723 return false;
3724 }
3725 const auto actionIndex = action >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3726 return isStylusToolType(properties[actionIndex].toolType);
3727}
3728
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003729NotifyMotionArgs TouchInputMapper::dispatchMotion(
3730 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3731 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003732 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3733 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003734 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003735 PointerCoords pointerCoords[MAX_POINTERS];
3736 PointerProperties pointerProperties[MAX_POINTERS];
3737 uint32_t pointerCount = 0;
3738 while (!idBits.isEmpty()) {
3739 uint32_t id = idBits.clearFirstMarkedBit();
3740 uint32_t index = idToIndex[id];
3741 pointerProperties[pointerCount].copyFrom(properties[index]);
3742 pointerCoords[pointerCount].copyFrom(coords[index]);
3743
3744 if (changedId >= 0 && id == uint32_t(changedId)) {
3745 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3746 }
3747
3748 pointerCount += 1;
3749 }
3750
3751 ALOG_ASSERT(pointerCount != 0);
3752
3753 if (changedId >= 0 && pointerCount == 1) {
3754 // Replace initial down and final up action.
3755 // We can compare the action without masking off the changed pointer index
3756 // because we know the index is 0.
3757 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3758 action = AMOTION_EVENT_ACTION_DOWN;
3759 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003760 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3761 action = AMOTION_EVENT_ACTION_CANCEL;
3762 } else {
3763 action = AMOTION_EVENT_ACTION_UP;
3764 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003765 } else {
3766 // Can't happen.
3767 ALOG_ASSERT(false);
3768 }
3769 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003770
3771 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3772 const bool showDirectStylusPointer = mConfig.stylusPointerIconEnabled &&
3773 mDeviceMode == DeviceMode::DIRECT && isStylusEvent(source, action, pointerProperties) &&
Seunghwan Choi356026c2023-02-01 14:37:25 +09003774 mPointerController && displayId != ADISPLAY_ID_NONE &&
3775 displayId == mPointerController->getDisplayId();
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003776 if (showDirectStylusPointer) {
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003777 switch (action & AMOTION_EVENT_ACTION_MASK) {
3778 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3779 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3780 mPointerController->setPresentation(
Seunghwan Choi75789cd2023-01-13 20:31:59 +09003781 PointerControllerInterface::Presentation::STYLUS_HOVER);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003782 mPointerController
3783 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[0].getX(),
3784 mCurrentCookedState.cookedPointerData.pointerCoords[0]
3785 .getY());
3786 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3787 break;
3788 case AMOTION_EVENT_ACTION_HOVER_EXIT:
3789 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
3790 break;
3791 }
3792 }
3793
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003794 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3795 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003796 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003797 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003798 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003799 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003800 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003801 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003802 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003803 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3804 policyFlags, action, actionButton, flags, metaState, buttonState,
3805 classification, edgeFlags, pointerCount, pointerProperties,
3806 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3807 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003808}
3809
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003810std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3811 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003812 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3813 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003814 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003815}
3816
Prabir Pradhan1728b212021-10-19 16:00:03 -07003817bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003818 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003819 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003820 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003821}
3822
3823const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3824 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003825 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3826 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3827 "left=%d, top=%d, right=%d, bottom=%d",
3828 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3829 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003830
3831 if (virtualKey.isHit(x, y)) {
3832 return &virtualKey;
3833 }
3834 }
3835
3836 return nullptr;
3837}
3838
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003839void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3840 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3841 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003842
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003843 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003844
3845 if (currentPointerCount == 0) {
3846 // No pointers to assign.
3847 return;
3848 }
3849
3850 if (lastPointerCount == 0) {
3851 // All pointers are new.
3852 for (uint32_t i = 0; i < currentPointerCount; i++) {
3853 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003854 current.rawPointerData.pointers[i].id = id;
3855 current.rawPointerData.idToIndex[id] = i;
3856 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003857 }
3858 return;
3859 }
3860
3861 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003862 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003863 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003864 uint32_t id = last.rawPointerData.pointers[0].id;
3865 current.rawPointerData.pointers[0].id = id;
3866 current.rawPointerData.idToIndex[id] = 0;
3867 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003868 return;
3869 }
3870
3871 // General case.
3872 // We build a heap of squared euclidean distances between current and last pointers
3873 // associated with the current and last pointer indices. Then, we find the best
3874 // match (by distance) for each current pointer.
3875 // The pointers must have the same tool type but it is possible for them to
3876 // transition from hovering to touching or vice-versa while retaining the same id.
3877 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3878
3879 uint32_t heapSize = 0;
3880 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3881 currentPointerIndex++) {
3882 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3883 lastPointerIndex++) {
3884 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003885 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003886 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003887 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003888 if (currentPointer.toolType == lastPointer.toolType) {
3889 int64_t deltaX = currentPointer.x - lastPointer.x;
3890 int64_t deltaY = currentPointer.y - lastPointer.y;
3891
3892 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3893
3894 // Insert new element into the heap (sift up).
3895 heap[heapSize].currentPointerIndex = currentPointerIndex;
3896 heap[heapSize].lastPointerIndex = lastPointerIndex;
3897 heap[heapSize].distance = distance;
3898 heapSize += 1;
3899 }
3900 }
3901 }
3902
3903 // Heapify
3904 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3905 startIndex -= 1;
3906 for (uint32_t parentIndex = startIndex;;) {
3907 uint32_t childIndex = parentIndex * 2 + 1;
3908 if (childIndex >= heapSize) {
3909 break;
3910 }
3911
3912 if (childIndex + 1 < heapSize &&
3913 heap[childIndex + 1].distance < heap[childIndex].distance) {
3914 childIndex += 1;
3915 }
3916
3917 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3918 break;
3919 }
3920
3921 swap(heap[parentIndex], heap[childIndex]);
3922 parentIndex = childIndex;
3923 }
3924 }
3925
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003926 if (DEBUG_POINTER_ASSIGNMENT) {
3927 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3928 for (size_t i = 0; i < heapSize; i++) {
3929 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3930 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3931 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003932 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003933
3934 // Pull matches out by increasing order of distance.
3935 // To avoid reassigning pointers that have already been matched, the loop keeps track
3936 // of which last and current pointers have been matched using the matchedXXXBits variables.
3937 // It also tracks the used pointer id bits.
3938 BitSet32 matchedLastBits(0);
3939 BitSet32 matchedCurrentBits(0);
3940 BitSet32 usedIdBits(0);
3941 bool first = true;
3942 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3943 while (heapSize > 0) {
3944 if (first) {
3945 // The first time through the loop, we just consume the root element of
3946 // the heap (the one with smallest distance).
3947 first = false;
3948 } else {
3949 // Previous iterations consumed the root element of the heap.
3950 // Pop root element off of the heap (sift down).
3951 heap[0] = heap[heapSize];
3952 for (uint32_t parentIndex = 0;;) {
3953 uint32_t childIndex = parentIndex * 2 + 1;
3954 if (childIndex >= heapSize) {
3955 break;
3956 }
3957
3958 if (childIndex + 1 < heapSize &&
3959 heap[childIndex + 1].distance < heap[childIndex].distance) {
3960 childIndex += 1;
3961 }
3962
3963 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3964 break;
3965 }
3966
3967 swap(heap[parentIndex], heap[childIndex]);
3968 parentIndex = childIndex;
3969 }
3970
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003971 if (DEBUG_POINTER_ASSIGNMENT) {
3972 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3973 for (size_t j = 0; j < heapSize; j++) {
3974 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3975 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3976 heap[j].distance);
3977 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003978 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003979 }
3980
3981 heapSize -= 1;
3982
3983 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3984 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3985
3986 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3987 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3988
3989 matchedCurrentBits.markBit(currentPointerIndex);
3990 matchedLastBits.markBit(lastPointerIndex);
3991
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003992 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3993 current.rawPointerData.pointers[currentPointerIndex].id = id;
3994 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3995 current.rawPointerData.markIdBit(id,
3996 current.rawPointerData.isHovering(
3997 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003998 usedIdBits.markBit(id);
3999
Harry Cutts45483602022-08-24 14:36:48 +00004000 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4001 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4002 ", distance=%" PRIu64,
4003 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004004 break;
4005 }
4006 }
4007
4008 // Assign fresh ids to pointers that were not matched in the process.
4009 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4010 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4011 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4012
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004013 current.rawPointerData.pointers[currentPointerIndex].id = id;
4014 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4015 current.rawPointerData.markIdBit(id,
4016 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004017
Harry Cutts45483602022-08-24 14:36:48 +00004018 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4019 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4020 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004021 }
4022}
4023
4024int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4025 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4026 return AKEY_STATE_VIRTUAL;
4027 }
4028
4029 for (const VirtualKey& virtualKey : mVirtualKeys) {
4030 if (virtualKey.keyCode == keyCode) {
4031 return AKEY_STATE_UP;
4032 }
4033 }
4034
4035 return AKEY_STATE_UNKNOWN;
4036}
4037
4038int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4039 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4040 return AKEY_STATE_VIRTUAL;
4041 }
4042
4043 for (const VirtualKey& virtualKey : mVirtualKeys) {
4044 if (virtualKey.scanCode == scanCode) {
4045 return AKEY_STATE_UP;
4046 }
4047 }
4048
4049 return AKEY_STATE_UNKNOWN;
4050}
4051
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004052bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4053 const std::vector<int32_t>& keyCodes,
4054 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004055 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004056 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004057 if (virtualKey.keyCode == keyCodes[i]) {
4058 outFlags[i] = 1;
4059 }
4060 }
4061 }
4062
4063 return true;
4064}
4065
4066std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4067 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004068 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004069 return std::make_optional(mPointerController->getDisplayId());
4070 } else {
4071 return std::make_optional(mViewport.displayId);
4072 }
4073 }
4074 return std::nullopt;
4075}
4076
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004077} // namespace android