blob: fffc5e0f4e3c30ddfd7ef9e68ab8add4d6662248 [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 Pradhan3e798762022-12-02 21:02:11 +0000845 constexpr auto isRotated = [](const ui::Transform::RotationFlags& rotation) {
846 return rotation == ui::Transform::ROT_90 || rotation == ui::Transform::ROT_270;
847 };
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000848
Prabir Pradhan3e798762022-12-02 21:02:11 +0000849 // See notes about input coordinates in the inputflinger docs:
850 // //frameworks/native/services/inputflinger/docs/input_coordinates.md
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000851
852 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
Prabir Pradhan3e798762022-12-02 21:02:11 +0000853 ui::Transform undoOffsetInRaw;
854 undoOffsetInRaw.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000855
Prabir Pradhan3e798762022-12-02 21:02:11 +0000856 // Step 2: Rotate the raw coordinates to account for input device orientation. The coordinates
857 // will now be in the same orientation as the display in ROTATION_0.
858 // Note: Negating an ui::Rotation value will give its inverse rotation.
859 const auto inputDeviceOrientation = ui::Transform::toRotationFlags(-mParameters.orientation);
860 const ui::Size orientedRawSize = isRotated(inputDeviceOrientation)
861 ? ui::Size{mRawPointerAxes.getRawHeight(), mRawPointerAxes.getRawWidth()}
862 : ui::Size{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
863 // When rotating raw values, account for the extra unit added when calculating the raw range.
864 const auto orientInRaw = ui::Transform(inputDeviceOrientation, orientedRawSize.width - 1,
865 orientedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000866
Prabir Pradhan3e798762022-12-02 21:02:11 +0000867 // Step 3: Rotate the raw coordinates to account for the display rotation. The coordinates will
868 // now be in the same orientation as the rotated display. There is no need to rotate the
869 // coordinates to the display rotation if the device is not orientation-aware.
870 const auto viewportRotation = ui::Transform::toRotationFlags(-mViewport.orientation);
871 const auto rotatedRawSize = mParameters.orientationAware && isRotated(viewportRotation)
872 ? ui::Size{orientedRawSize.height, orientedRawSize.width}
873 : orientedRawSize;
874 // When rotating raw values, account for the extra unit added when calculating the raw range.
875 const auto rotateInRaw = mParameters.orientationAware
876 ? ui::Transform(viewportRotation, rotatedRawSize.width - 1, rotatedRawSize.height - 1)
877 : ui::Transform();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000878
Prabir Pradhan3e798762022-12-02 21:02:11 +0000879 // Step 4: Scale the raw coordinates to the display space.
880 // - Here, we assume that the raw surface of the touch device maps perfectly to the surface
881 // of the display panel. This is usually true for touchscreens.
882 // - From this point onward, we are no longer in the discrete space of the raw coordinates but
883 // are in the continuous space of the logical display.
884 ui::Transform scaleRawToDisplay;
885 const float xScale = static_cast<float>(mViewport.deviceWidth) / rotatedRawSize.width;
886 const float yScale = static_cast<float>(mViewport.deviceHeight) / rotatedRawSize.height;
887 scaleRawToDisplay.set(xScale, 0, 0, yScale);
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000888
Prabir Pradhan3e798762022-12-02 21:02:11 +0000889 // Step 5: Undo the display rotation to bring us back to the un-rotated display coordinate space
890 // that InputReader uses.
891 const auto undoRotateInDisplay =
892 ui::Transform(viewportRotation, mViewport.deviceWidth, mViewport.deviceHeight)
893 .inverse();
894
895 // Now put it all together!
896 mRawToRotatedDisplay = (scaleRawToDisplay * (rotateInRaw * (orientInRaw * undoOffsetInRaw)));
897 mRawToDisplay = (undoRotateInDisplay * mRawToRotatedDisplay);
898 mRawRotation = ui::Transform{mRawToDisplay.getOrientation()};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000899}
900
Prabir Pradhan1728b212021-10-19 16:00:03 -0700901void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000902 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700903
904 resolveExternalStylusPresence();
905
906 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100907 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000908 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700909 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100910 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700911 if (hasStylus()) {
912 mSource |= AINPUT_SOURCE_STYLUS;
913 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800914 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700915 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100916 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700917 if (hasStylus()) {
918 mSource |= AINPUT_SOURCE_STYLUS;
919 }
920 if (hasExternalStylus()) {
921 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
922 }
Michael Wright227c5542020-07-02 18:30:52 +0100923 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700924 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100925 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700926 } else {
927 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100928 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700929 }
930
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000931 const std::optional<DisplayViewport> newViewportOpt = findViewport();
932
933 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700934 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
935 ALOGW("Touch device '%s' did not report support for X or Y axis! "
936 "The device will be inoperable.",
937 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100938 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000939 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700940 ALOGI("Touch device '%s' could not query the properties of its associated "
941 "display. The device will be inoperable until the display size "
942 "becomes available.",
943 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100944 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700945 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000946 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
947 getDeviceName().c_str(), getDeviceId());
948 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000949 }
950
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700951 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000952 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000953 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
954 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
955 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
956 const float rawMeanResolution =
957 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700958
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000959 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
960 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700961 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700962 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000963 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
964 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
965 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700966
Michael Wright227c5542020-07-02 18:30:52 +0100967 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000968 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700969
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000970 mDisplayBounds = getNaturalDisplaySize(mViewport);
971 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
972 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700973
Prabir Pradhan3e798762022-12-02 21:02:11 +0000974 // TODO(b/257118693): Remove the dependence on the old orientation/rotation logic that
975 // uses mInputDeviceOrientation. The new logic uses the transforms calculated in
976 // computeInputTransforms().
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000977 // InputReader works in the un-rotated display coordinate space, so we don't need to do
978 // anything if the device is already orientation-aware. If the device is not
979 // orientation-aware, then we need to apply the inverse rotation of the display so that
980 // when the display rotation is applied later as a part of the per-window transform, we
981 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700982 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +0000983 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000984 : getInverseRotation(mViewport.orientation);
985 // For orientation-aware devices that work in the un-rotated coordinate space, the
986 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000987 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000988 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700989
990 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +0000991 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000992 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700993 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000994 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000995 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +0000996 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000997 mRawToDisplay.reset();
998 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000999 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001000 }
1001 }
1002
1003 // If moving between pointer modes, need to reset some state.
1004 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1005 if (deviceModeChanged) {
1006 mOrientedRanges.clear();
1007 }
1008
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001009 // Create and preserve the pointer controller in the following cases:
1010 const bool isPointerControllerNeeded =
1011 // - when the device is in pointer mode, to show the mouse cursor;
1012 (mDeviceMode == DeviceMode::POINTER) ||
1013 // - when pointer capture is enabled, to preserve the mouse cursor position;
1014 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
1015 mConfig.pointerCaptureRequest.enable) ||
1016 // - when we should be showing touches;
1017 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
1018 // - when we should be showing a pointer icon for direct styluses.
1019 (mDeviceMode == DeviceMode::DIRECT && mConfig.stylusPointerIconEnabled && hasStylus());
1020 if (isPointerControllerNeeded) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001021 if (mPointerController == nullptr) {
1022 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001023 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001024 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001025 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1026 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001027 } else {
lilinnandef700b2022-06-17 19:32:01 +08001028 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1029 !mConfig.showTouches) {
1030 mPointerController->clearSpots();
1031 }
Michael Wright17db18e2020-06-26 20:51:44 +01001032 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001033 }
1034
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001035 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001036 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001037 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001038 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001039 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001040
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001041 configureVirtualKeys();
1042
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001043 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001044
1045 // Location
1046 updateAffineTransformation();
1047
Michael Wright227c5542020-07-02 18:30:52 +01001048 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001049 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001050 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1051 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001052
1053 // Scale movements such that one whole swipe of the touch pad covers a
1054 // given area relative to the diagonal size of the display when no acceleration
1055 // is applied.
1056 // Assume that the touch pad has a square aspect ratio such that movements in
1057 // X and Y of the same number of raw units cover the same physical distance.
1058 mPointerXMovementScale =
1059 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1060 mPointerYMovementScale = mPointerXMovementScale;
1061
1062 // Scale zooms to cover a smaller range of the display than movements do.
1063 // This value determines the area around the pointer that is affected by freeform
1064 // pointer gestures.
1065 mPointerXZoomScale =
1066 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1067 mPointerYZoomScale = mPointerXZoomScale;
1068
HQ Liue6983c72022-04-19 22:14:56 +00001069 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1070 // axis is non positive value.
1071 const float minFreeformGestureWidth =
1072 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1073
1074 mPointerGestureMaxSwipeWidth =
1075 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1076 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001077 }
1078
1079 // Inform the dispatcher about the changes.
1080 *outResetNeeded = true;
1081 bumpGeneration();
1082 }
1083}
1084
Prabir Pradhan1728b212021-10-19 16:00:03 -07001085void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001086 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001087 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001088 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1089 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001090 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001091}
1092
1093void TouchInputMapper::configureVirtualKeys() {
1094 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001095 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001096
1097 mVirtualKeys.clear();
1098
1099 if (virtualKeyDefinitions.size() == 0) {
1100 return;
1101 }
1102
1103 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1104 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1105 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1106 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1107
1108 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1109 VirtualKey virtualKey;
1110
1111 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1112 int32_t keyCode;
1113 int32_t dummyKeyMetaState;
1114 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001115 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1116 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001117 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1118 continue; // drop the key
1119 }
1120
1121 virtualKey.keyCode = keyCode;
1122 virtualKey.flags = flags;
1123
1124 // convert the key definition's display coordinates into touch coordinates for a hit box
1125 int32_t halfWidth = virtualKeyDefinition.width / 2;
1126 int32_t halfHeight = virtualKeyDefinition.height / 2;
1127
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001128 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1129 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001130 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001131 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1132 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001133 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001134 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1135 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001136 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001137 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1138 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139 touchScreenTop;
1140 mVirtualKeys.push_back(virtualKey);
1141 }
1142}
1143
1144void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1145 if (!mVirtualKeys.empty()) {
1146 dump += INDENT3 "Virtual Keys:\n";
1147
1148 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1149 const VirtualKey& virtualKey = mVirtualKeys[i];
1150 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1151 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1152 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1153 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1154 }
1155 }
1156}
1157
1158void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001159 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001160 Calibration& out = mCalibration;
1161
1162 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001163 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001164 std::string sizeCalibrationString;
1165 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001166 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001167 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001168 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001169 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001173 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001175 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001177 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001178 }
1179 }
1180
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001181 float sizeScale;
1182
1183 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1184 out.sizeScale = sizeScale;
1185 }
1186 float sizeBias;
1187 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1188 out.sizeBias = sizeBias;
1189 }
1190 bool sizeIsSummed;
1191 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1192 out.sizeIsSummed = sizeIsSummed;
1193 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001194
1195 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001196 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001197 std::string pressureCalibrationString;
1198 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001199 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001201 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001202 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001203 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001204 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 } else if (pressureCalibrationString != "default") {
1206 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001207 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001208 }
1209 }
1210
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001211 float pressureScale;
1212 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1213 out.pressureScale = pressureScale;
1214 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001215
1216 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001217 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001218 std::string orientationCalibrationString;
1219 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001220 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001221 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001222 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001223 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001224 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001225 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001226 } else if (orientationCalibrationString != "default") {
1227 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001228 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229 }
1230 }
1231
1232 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001233 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001234 std::string distanceCalibrationString;
1235 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001236 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001237 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001238 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001239 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001240 } else if (distanceCalibrationString != "default") {
1241 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001242 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001243 }
1244 }
1245
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001246 float distanceScale;
1247 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1248 out.distanceScale = distanceScale;
1249 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001250}
1251
1252void TouchInputMapper::resolveCalibration() {
1253 // Size
1254 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001255 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1256 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001257 }
1258 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001259 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001260 }
1261
1262 // Pressure
1263 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001264 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1265 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001266 }
1267 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001268 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001269 }
1270
1271 // Orientation
1272 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001273 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1274 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001275 }
1276 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001277 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001278 }
1279
1280 // Distance
1281 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001282 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1283 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284 }
1285 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001286 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001288}
1289
1290void TouchInputMapper::dumpCalibration(std::string& dump) {
1291 dump += INDENT3 "Calibration:\n";
1292
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001293 dump += INDENT4 "touch.size.calibration: ";
1294 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001295
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001296 if (mCalibration.sizeScale) {
1297 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 }
1299
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001300 if (mCalibration.sizeBias) {
1301 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001302 }
1303
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001304 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001305 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001306 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 }
1308
1309 // Pressure
1310 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001311 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001312 dump += INDENT4 "touch.pressure.calibration: none\n";
1313 break;
Michael Wright227c5542020-07-02 18:30:52 +01001314 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001315 dump += INDENT4 "touch.pressure.calibration: physical\n";
1316 break;
Michael Wright227c5542020-07-02 18:30:52 +01001317 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001318 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1319 break;
1320 default:
1321 ALOG_ASSERT(false);
1322 }
1323
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001324 if (mCalibration.pressureScale) {
1325 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001326 }
1327
1328 // Orientation
1329 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001330 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 dump += INDENT4 "touch.orientation.calibration: none\n";
1332 break;
Michael Wright227c5542020-07-02 18:30:52 +01001333 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001334 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1335 break;
Michael Wright227c5542020-07-02 18:30:52 +01001336 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001337 dump += INDENT4 "touch.orientation.calibration: vector\n";
1338 break;
1339 default:
1340 ALOG_ASSERT(false);
1341 }
1342
1343 // Distance
1344 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001345 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001346 dump += INDENT4 "touch.distance.calibration: none\n";
1347 break;
Michael Wright227c5542020-07-02 18:30:52 +01001348 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001349 dump += INDENT4 "touch.distance.calibration: scaled\n";
1350 break;
1351 default:
1352 ALOG_ASSERT(false);
1353 }
1354
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001355 if (mCalibration.distanceScale) {
1356 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001357 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001358}
1359
1360void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1361 dump += INDENT3 "Affine Transformation:\n";
1362
1363 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1364 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1365 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1366 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1367 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1368 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1369}
1370
1371void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001372 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001373 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001374}
1375
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001376std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001377 std::list<NotifyArgs> out = cancelTouch(when, when);
1378 updateTouchSpots();
1379
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001380 mCursorButtonAccumulator.reset(getDeviceContext());
1381 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001382 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001383
1384 mPointerVelocityControl.reset();
1385 mWheelXVelocityControl.reset();
1386 mWheelYVelocityControl.reset();
1387
1388 mRawStatesPending.clear();
1389 mCurrentRawState.clear();
1390 mCurrentCookedState.clear();
1391 mLastRawState.clear();
1392 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001393 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001394 mSentHoverEnter = false;
1395 mHavePointerIds = false;
1396 mCurrentMotionAborted = false;
1397 mDownTime = 0;
1398
1399 mCurrentVirtualKey.down = false;
1400
1401 mPointerGesture.reset();
1402 mPointerSimple.reset();
1403 resetExternalStylus();
1404
1405 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001406 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001407 mPointerController->clearSpots();
1408 }
1409
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001410 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001411}
1412
1413void TouchInputMapper::resetExternalStylus() {
1414 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001415 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001416 mExternalStylusFusionTimeout = LLONG_MAX;
1417 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001418 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001419}
1420
1421void TouchInputMapper::clearStylusDataPendingFlags() {
1422 mExternalStylusDataPending = false;
1423 mExternalStylusFusionTimeout = LLONG_MAX;
1424}
1425
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001426std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001427 mCursorButtonAccumulator.process(rawEvent);
1428 mCursorScrollAccumulator.process(rawEvent);
1429 mTouchButtonAccumulator.process(rawEvent);
1430
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001431 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001432 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001433 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001434 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001435 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001436}
1437
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001438std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1439 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001440 if (mDeviceMode == DeviceMode::DISABLED) {
1441 // Only save the last pending state when the device is disabled.
1442 mRawStatesPending.clear();
1443 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001444 // Push a new state.
1445 mRawStatesPending.emplace_back();
1446
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001447 RawState& next = mRawStatesPending.back();
1448 next.clear();
1449 next.when = when;
1450 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001451
1452 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001453 next.buttonState = filterButtonState(mConfig,
1454 mTouchButtonAccumulator.getButtonState() |
1455 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001456
1457 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001458 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1459 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001460 mCursorScrollAccumulator.finishSync();
1461
1462 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001463 syncTouch(when, &next);
1464
1465 // The last RawState is the actually second to last, since we just added a new state
1466 const RawState& last =
1467 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001468
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001469 std::tie(next.when, next.readTime) =
1470 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1471 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001472
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001473 // Assign pointer ids.
1474 if (!mHavePointerIds) {
1475 assignPointerIds(last, next);
1476 }
1477
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001478 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001479 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1480 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1481 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1482 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1483 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1484 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001485
Arthur Hung9ad18942021-06-19 02:04:46 +00001486 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1487 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1488 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1489 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1490 next.rawPointerData.hoveringIdBits.value);
1491 }
1492
Harry Cutts33476232023-01-30 19:57:29 +00001493 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001494 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001495}
1496
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001497std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1498 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001499 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001500 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001501 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001502 }
1503
1504 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1505 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1506 // touching the current state will only observe the events that have been dispatched to the
1507 // rest of the pipeline.
1508 const size_t N = mRawStatesPending.size();
1509 size_t count;
1510 for (count = 0; count < N; count++) {
1511 const RawState& next = mRawStatesPending[count];
1512
1513 // A failure to assign the stylus id means that we're waiting on stylus data
1514 // and so should defer the rest of the pipeline.
1515 if (assignExternalStylusId(next, timeout)) {
1516 break;
1517 }
1518
1519 // All ready to go.
1520 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001521 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001522 if (mCurrentRawState.when < mLastRawState.when) {
1523 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001524 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001525 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001526 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001527 }
1528 if (count != 0) {
1529 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1530 }
1531
1532 if (mExternalStylusDataPending) {
1533 if (timeout) {
1534 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1535 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001536 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001537 ALOGD_IF(DEBUG_STYLUS_FUSION,
1538 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001539 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001540 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001541 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1542 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1543 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1544 }
1545 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001546 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001547}
1548
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001549std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1550 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001551 // Always start with a clean state.
1552 mCurrentCookedState.clear();
1553
1554 // Apply stylus buttons to current raw state.
1555 applyExternalStylusButtonState(when);
1556
1557 // Handle policy on initial down or hover events.
1558 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1559 mCurrentRawState.rawPointerData.pointerCount != 0;
1560
1561 uint32_t policyFlags = 0;
1562 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1563 if (initialDown || buttonsPressed) {
1564 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001565 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001566 getContext()->fadePointer();
1567 }
1568
1569 if (mParameters.wake) {
1570 policyFlags |= POLICY_FLAG_WAKE;
1571 }
1572 }
1573
1574 // Consume raw off-screen touches before cooking pointer data.
1575 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001576 bool consumed;
1577 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1578 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001579 mCurrentRawState.rawPointerData.clear();
1580 }
1581
1582 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1583 // with cooked pointer data that has the same ids and indices as the raw data.
1584 // The following code can use either the raw or cooked data, as needed.
1585 cookPointerData();
1586
1587 // Apply stylus pressure to current cooked state.
1588 applyExternalStylusTouchState(when);
1589
1590 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001591 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1592 mSource, mViewport.displayId, policyFlags,
1593 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001594
1595 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001596 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001597 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1598 uint32_t id = idBits.clearFirstMarkedBit();
1599 const RawPointerData::Pointer& pointer =
1600 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001601 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001602 mCurrentCookedState.stylusIdBits.markBit(id);
1603 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1604 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1605 mCurrentCookedState.fingerIdBits.markBit(id);
1606 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1607 mCurrentCookedState.mouseIdBits.markBit(id);
1608 }
1609 }
1610 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1611 uint32_t id = idBits.clearFirstMarkedBit();
1612 const RawPointerData::Pointer& pointer =
1613 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001614 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001615 mCurrentCookedState.stylusIdBits.markBit(id);
1616 }
1617 }
1618
1619 // Stylus takes precedence over all tools, then mouse, then finger.
1620 PointerUsage pointerUsage = mPointerUsage;
1621 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1622 mCurrentCookedState.mouseIdBits.clear();
1623 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001624 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001625 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1626 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001627 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001628 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1629 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001630 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001631 }
1632
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001633 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001634 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001635 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001636 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001637 out += dispatchButtonRelease(when, readTime, policyFlags);
1638 out += dispatchHoverExit(when, readTime, policyFlags);
1639 out += dispatchTouches(when, readTime, policyFlags);
1640 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1641 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001642 }
1643
1644 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1645 mCurrentMotionAborted = false;
1646 }
1647 }
1648
1649 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001650 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1651 mSource, mViewport.displayId, policyFlags,
1652 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001653
1654 // Clear some transient state.
1655 mCurrentRawState.rawVScroll = 0;
1656 mCurrentRawState.rawHScroll = 0;
1657
1658 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001659 mLastRawState = mCurrentRawState;
1660 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001661 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001662}
1663
Garfield Tanc734e4f2021-01-15 20:01:39 -08001664void TouchInputMapper::updateTouchSpots() {
1665 if (!mConfig.showTouches || mPointerController == nullptr) {
1666 return;
1667 }
1668
1669 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1670 // clear touch spots.
1671 if (mDeviceMode != DeviceMode::DIRECT &&
1672 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1673 return;
1674 }
1675
1676 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1677 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1678
1679 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001680 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1681 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhanb3ce4532023-03-03 22:20:54 +00001682 mCurrentCookedState.cookedPointerData.touchingIdBits |
1683 mCurrentCookedState.cookedPointerData.hoveringIdBits,
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001684 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001685}
1686
1687bool TouchInputMapper::isTouchScreen() {
1688 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1689 mParameters.hasAssociatedDisplay;
1690}
1691
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001692void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001693 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1694 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001695 const int32_t pressedButtons =
1696 filterButtonState(mConfig,
1697 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001698 const int32_t releasedButtons =
1699 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1700
1701 mCurrentRawState.buttonState |= pressedButtons;
1702 mCurrentRawState.buttonState &= ~releasedButtons;
1703
1704 mExternalStylusButtonsApplied |= pressedButtons;
1705 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001706 }
1707}
1708
1709void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1710 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1711 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001712 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1713 return;
1714 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001715
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001716 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1717 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1718 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1719 : 0.f;
1720 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1721 pressure = *mExternalStylusState.pressure;
1722 }
1723 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1724 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001725
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001726 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001727 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001728 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001729 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001730 }
1731}
1732
1733bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001734 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001735 return false;
1736 }
1737
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001738 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001739 if (mFusedStylusPointerId &&
1740 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001741 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001742 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001743 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001744 }
1745
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001746 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1747 state.rawPointerData.pointerCount != 0;
1748 if (!initialDown) {
1749 return false;
1750 }
1751
1752 if (!mExternalStylusState.pressure) {
1753 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1754 return false;
1755 }
1756
1757 if (*mExternalStylusState.pressure != 0.0f) {
1758 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1759 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1760 return false;
1761 }
1762
1763 if (timeout) {
1764 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1765 mFusedStylusPointerId.reset();
1766 mExternalStylusFusionTimeout = LLONG_MAX;
1767 return false;
1768 }
1769
1770 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1771 // being processed until we either get pressure data or timeout.
1772 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1773 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1774 }
1775 ALOGD_IF(DEBUG_STYLUS_FUSION,
1776 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1777 mExternalStylusFusionTimeout);
1778 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1779 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001780}
1781
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001782std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1783 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001784 if (mDeviceMode == DeviceMode::POINTER) {
1785 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001786 // Since this is a synthetic event, we can consider its latency to be zero
1787 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001788 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001789 }
Michael Wright227c5542020-07-02 18:30:52 +01001790 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001791 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001792 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001793 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1794 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1795 }
1796 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001797 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001798}
1799
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001800std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1801 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001802 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001803 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001804 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001805 // The following three cases are handled here:
1806 // - We're in the middle of a fused stream of data;
1807 // - We're waiting on external stylus data before dispatching the initial down; or
1808 // - Only the button state, which is not reported through a specific pointer, has changed.
1809 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001810 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001811 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001812 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001813 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001814}
1815
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001816std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1817 uint32_t policyFlags, bool& outConsumed) {
1818 outConsumed = false;
1819 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001820 // Check for release of a virtual key.
1821 if (mCurrentVirtualKey.down) {
1822 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1823 // Pointer went up while virtual key was down.
1824 mCurrentVirtualKey.down = false;
1825 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001826 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1827 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1828 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001829 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1830 AKEY_EVENT_FLAG_FROM_SYSTEM |
1831 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001832 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001833 outConsumed = true;
1834 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001835 }
1836
1837 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1838 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1839 const RawPointerData::Pointer& pointer =
1840 mCurrentRawState.rawPointerData.pointerForId(id);
1841 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1842 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1843 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001844 outConsumed = true;
1845 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001846 }
1847 }
1848
1849 // Pointer left virtual key area or another pointer also went down.
1850 // Send key cancellation but do not consume the touch yet.
1851 // This is useful when the user swipes through from the virtual key area
1852 // into the main display surface.
1853 mCurrentVirtualKey.down = false;
1854 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001855 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1856 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001857 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1858 AKEY_EVENT_FLAG_FROM_SYSTEM |
1859 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1860 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001861 }
1862 }
1863
1864 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1865 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1866 // Pointer just went down. Check for virtual key press or off-screen touches.
1867 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1868 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001869 // Skip checking whether the pointer is inside the physical frame if the device is in
1870 // unscaled mode.
1871 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1872 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001873 // If exactly one pointer went down, check for virtual key hit.
1874 // Otherwise we will drop the entire stroke.
1875 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1876 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1877 if (virtualKey) {
1878 mCurrentVirtualKey.down = true;
1879 mCurrentVirtualKey.downTime = when;
1880 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1881 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1882 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001883 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1884 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001885
1886 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001887 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1888 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1889 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001890 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1891 AKEY_EVENT_ACTION_DOWN,
1892 AKEY_EVENT_FLAG_FROM_SYSTEM |
1893 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001894 }
1895 }
1896 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001897 outConsumed = true;
1898 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001899 }
1900 }
1901
1902 // Disable all virtual key touches that happen within a short time interval of the
1903 // most recent touch within the screen area. The idea is to filter out stray
1904 // virtual key presses when interacting with the touch screen.
1905 //
1906 // Problems we're trying to solve:
1907 //
1908 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1909 // virtual key area that is implemented by a separate touch panel and accidentally
1910 // triggers a virtual key.
1911 //
1912 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1913 // area and accidentally triggers a virtual key. This often happens when virtual keys
1914 // are layed out below the screen near to where the on screen keyboard's space bar
1915 // is displayed.
1916 if (mConfig.virtualKeyQuietTime > 0 &&
1917 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001918 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001919 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001920 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001921}
1922
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001923NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1924 uint32_t policyFlags, int32_t keyEventAction,
1925 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001926 int32_t keyCode = mCurrentVirtualKey.keyCode;
1927 int32_t scanCode = mCurrentVirtualKey.scanCode;
1928 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001929 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001930 policyFlags |= POLICY_FLAG_VIRTUAL;
1931
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001932 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1933 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1934 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001935}
1936
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001937std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1938 uint32_t policyFlags) {
1939 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001940 if (mCurrentMotionAborted) {
1941 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001942 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001943 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001944 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1945 if (!currentIdBits.isEmpty()) {
1946 int32_t metaState = getContext()->getGlobalMetaState();
1947 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001948 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001949 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1950 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001951 mCurrentCookedState.cookedPointerData.pointerProperties,
1952 mCurrentCookedState.cookedPointerData.pointerCoords,
1953 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1954 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1955 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001956 mCurrentMotionAborted = true;
1957 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001958 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001959}
1960
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001961// Updates pointer coords and properties for pointers with specified ids that have moved.
1962// Returns true if any of them changed.
1963static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1964 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1965 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1966 BitSet32 idBits) {
1967 bool changed = false;
1968 while (!idBits.isEmpty()) {
1969 uint32_t id = idBits.clearFirstMarkedBit();
1970 uint32_t inIndex = inIdToIndex[id];
1971 uint32_t outIndex = outIdToIndex[id];
1972
1973 const PointerProperties& curInProperties = inProperties[inIndex];
1974 const PointerCoords& curInCoords = inCoords[inIndex];
1975 PointerProperties& curOutProperties = outProperties[outIndex];
1976 PointerCoords& curOutCoords = outCoords[outIndex];
1977
1978 if (curInProperties != curOutProperties) {
1979 curOutProperties.copyFrom(curInProperties);
1980 changed = true;
1981 }
1982
1983 if (curInCoords != curOutCoords) {
1984 curOutCoords.copyFrom(curInCoords);
1985 changed = true;
1986 }
1987 }
1988 return changed;
1989}
1990
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001991std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1992 uint32_t policyFlags) {
1993 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001994 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1995 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1996 int32_t metaState = getContext()->getGlobalMetaState();
1997 int32_t buttonState = mCurrentCookedState.buttonState;
1998
1999 if (currentIdBits == lastIdBits) {
2000 if (!currentIdBits.isEmpty()) {
2001 // No pointer id changes so this is a move event.
2002 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002003 out.push_back(
2004 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2005 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2006 mCurrentCookedState.cookedPointerData.pointerProperties,
2007 mCurrentCookedState.cookedPointerData.pointerCoords,
2008 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2009 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2010 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002011 }
2012 } else {
2013 // There may be pointers going up and pointers going down and pointers moving
2014 // all at the same time.
2015 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2016 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2017 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2018 BitSet32 dispatchedIdBits(lastIdBits.value);
2019
2020 // Update last coordinates of pointers that have moved so that we observe the new
2021 // pointer positions at the same time as other pointers that have just gone up.
2022 bool moveNeeded =
2023 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2024 mCurrentCookedState.cookedPointerData.pointerCoords,
2025 mCurrentCookedState.cookedPointerData.idToIndex,
2026 mLastCookedState.cookedPointerData.pointerProperties,
2027 mLastCookedState.cookedPointerData.pointerCoords,
2028 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2029 if (buttonState != mLastCookedState.buttonState) {
2030 moveNeeded = true;
2031 }
2032
2033 // Dispatch pointer up events.
2034 while (!upIdBits.isEmpty()) {
2035 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002036 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002037 if (isCanceled) {
2038 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2039 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002040 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2041 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2042 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2043 buttonState, 0,
2044 mLastCookedState.cookedPointerData.pointerProperties,
2045 mLastCookedState.cookedPointerData.pointerCoords,
2046 mLastCookedState.cookedPointerData.idToIndex,
2047 dispatchedIdBits, upId, mOrientedXPrecision,
2048 mOrientedYPrecision, mDownTime,
2049 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002050 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002051 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002052 }
2053
2054 // Dispatch move events if any of the remaining pointers moved from their old locations.
2055 // Although applications receive new locations as part of individual pointer up
2056 // events, they do not generally handle them except when presented in a move event.
2057 if (moveNeeded && !moveIdBits.isEmpty()) {
2058 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002059 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2060 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2061 mCurrentCookedState.cookedPointerData.pointerProperties,
2062 mCurrentCookedState.cookedPointerData.pointerCoords,
2063 mCurrentCookedState.cookedPointerData.idToIndex,
2064 dispatchedIdBits, -1, mOrientedXPrecision,
2065 mOrientedYPrecision, mDownTime,
2066 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002067 }
2068
2069 // Dispatch pointer down events using the new pointer locations.
2070 while (!downIdBits.isEmpty()) {
2071 uint32_t downId = downIdBits.clearFirstMarkedBit();
2072 dispatchedIdBits.markBit(downId);
2073
2074 if (dispatchedIdBits.count() == 1) {
2075 // First pointer is going down. Set down time.
2076 mDownTime = when;
2077 }
2078
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002079 out.push_back(
2080 dispatchMotion(when, readTime, policyFlags, mSource,
2081 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2082 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2083 mCurrentCookedState.cookedPointerData.pointerCoords,
2084 mCurrentCookedState.cookedPointerData.idToIndex,
2085 dispatchedIdBits, downId, mOrientedXPrecision,
2086 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002087 }
2088 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002089 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002090}
2091
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002092std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2093 uint32_t policyFlags) {
2094 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002095 if (mSentHoverEnter &&
2096 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2097 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2098 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002099 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2100 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2101 mLastCookedState.buttonState, 0,
2102 mLastCookedState.cookedPointerData.pointerProperties,
2103 mLastCookedState.cookedPointerData.pointerCoords,
2104 mLastCookedState.cookedPointerData.idToIndex,
2105 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2106 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2107 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002108 mSentHoverEnter = false;
2109 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002110 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002111}
2112
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002113std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2114 uint32_t policyFlags) {
2115 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002116 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2117 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2118 int32_t metaState = getContext()->getGlobalMetaState();
2119 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002120 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2121 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2122 mCurrentRawState.buttonState, 0,
2123 mCurrentCookedState.cookedPointerData.pointerProperties,
2124 mCurrentCookedState.cookedPointerData.pointerCoords,
2125 mCurrentCookedState.cookedPointerData.idToIndex,
2126 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2127 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2128 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002129 mSentHoverEnter = true;
2130 }
2131
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002132 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2133 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2134 mCurrentRawState.buttonState, 0,
2135 mCurrentCookedState.cookedPointerData.pointerProperties,
2136 mCurrentCookedState.cookedPointerData.pointerCoords,
2137 mCurrentCookedState.cookedPointerData.idToIndex,
2138 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2139 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2140 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002141 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002142 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002143}
2144
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002145std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2146 uint32_t policyFlags) {
2147 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002148 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2149 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2150 const int32_t metaState = getContext()->getGlobalMetaState();
2151 int32_t buttonState = mLastCookedState.buttonState;
2152 while (!releasedButtons.isEmpty()) {
2153 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2154 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002155 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2156 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2157 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002158 mLastCookedState.cookedPointerData.pointerProperties,
2159 mLastCookedState.cookedPointerData.pointerCoords,
2160 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002161 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2162 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002163 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002164 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002165}
2166
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002167std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2168 uint32_t policyFlags) {
2169 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002170 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2171 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2172 const int32_t metaState = getContext()->getGlobalMetaState();
2173 int32_t buttonState = mLastCookedState.buttonState;
2174 while (!pressedButtons.isEmpty()) {
2175 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2176 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002177 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2178 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2179 buttonState, 0,
2180 mCurrentCookedState.cookedPointerData.pointerProperties,
2181 mCurrentCookedState.cookedPointerData.pointerCoords,
2182 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2183 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2184 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002185 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002186 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002187}
2188
LiZhihong758eb562022-11-03 15:28:29 +08002189std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2190 uint32_t policyFlags,
2191 BitSet32 idBits,
2192 nsecs_t readTime) {
2193 std::list<NotifyArgs> out;
2194 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2195 const int32_t metaState = getContext()->getGlobalMetaState();
2196 int32_t buttonState = mLastCookedState.buttonState;
2197
2198 while (!releasedButtons.isEmpty()) {
2199 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2200 buttonState &= ~actionButton;
2201 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2202 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2203 metaState, buttonState, 0,
2204 mPointerGesture.lastGestureProperties,
2205 mPointerGesture.lastGestureCoords,
2206 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2207 mOrientedXPrecision, mOrientedYPrecision,
2208 mPointerGesture.downTime, MotionClassification::NONE));
2209 }
2210 return out;
2211}
2212
2213std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2214 uint32_t policyFlags,
2215 BitSet32 idBits,
2216 nsecs_t readTime) {
2217 std::list<NotifyArgs> out;
2218 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2219 const int32_t metaState = getContext()->getGlobalMetaState();
2220 int32_t buttonState = mLastCookedState.buttonState;
2221
2222 while (!pressedButtons.isEmpty()) {
2223 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2224 buttonState |= actionButton;
2225 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2226 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2227 buttonState, 0, mPointerGesture.currentGestureProperties,
2228 mPointerGesture.currentGestureCoords,
2229 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2230 mOrientedXPrecision, mOrientedYPrecision,
2231 mPointerGesture.downTime, MotionClassification::NONE));
2232 }
2233 return out;
2234}
2235
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002236const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2237 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2238 return cookedPointerData.touchingIdBits;
2239 }
2240 return cookedPointerData.hoveringIdBits;
2241}
2242
2243void TouchInputMapper::cookPointerData() {
2244 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2245
2246 mCurrentCookedState.cookedPointerData.clear();
2247 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2248 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2249 mCurrentRawState.rawPointerData.hoveringIdBits;
2250 mCurrentCookedState.cookedPointerData.touchingIdBits =
2251 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002252 mCurrentCookedState.cookedPointerData.canceledIdBits =
2253 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002254
2255 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2256 mCurrentCookedState.buttonState = 0;
2257 } else {
2258 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2259 }
2260
2261 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002262 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002263 for (uint32_t i = 0; i < currentPointerCount; i++) {
2264 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2265
2266 // Size
2267 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2268 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002269 case Calibration::SizeCalibration::GEOMETRIC:
2270 case Calibration::SizeCalibration::DIAMETER:
2271 case Calibration::SizeCalibration::BOX:
2272 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002273 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2274 touchMajor = in.touchMajor;
2275 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2276 toolMajor = in.toolMajor;
2277 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2278 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2279 : in.touchMajor;
2280 } else if (mRawPointerAxes.touchMajor.valid) {
2281 toolMajor = touchMajor = in.touchMajor;
2282 toolMinor = touchMinor =
2283 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2284 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2285 : in.touchMajor;
2286 } else if (mRawPointerAxes.toolMajor.valid) {
2287 touchMajor = toolMajor = in.toolMajor;
2288 touchMinor = toolMinor =
2289 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2290 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2291 : in.toolMajor;
2292 } else {
2293 ALOG_ASSERT(false,
2294 "No touch or tool axes. "
2295 "Size calibration should have been resolved to NONE.");
2296 touchMajor = 0;
2297 touchMinor = 0;
2298 toolMajor = 0;
2299 toolMinor = 0;
2300 size = 0;
2301 }
2302
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002303 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002304 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2305 if (touchingCount > 1) {
2306 touchMajor /= touchingCount;
2307 touchMinor /= touchingCount;
2308 toolMajor /= touchingCount;
2309 toolMinor /= touchingCount;
2310 size /= touchingCount;
2311 }
2312 }
2313
Michael Wright227c5542020-07-02 18:30:52 +01002314 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002315 touchMajor *= mGeometricScale;
2316 touchMinor *= mGeometricScale;
2317 toolMajor *= mGeometricScale;
2318 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002319 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002320 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2321 touchMinor = touchMajor;
2322 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2323 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002324 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002325 touchMinor = touchMajor;
2326 toolMinor = toolMajor;
2327 }
2328
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002329 mCalibration.applySizeScaleAndBias(touchMajor);
2330 mCalibration.applySizeScaleAndBias(touchMinor);
2331 mCalibration.applySizeScaleAndBias(toolMajor);
2332 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002333 size *= mSizeScale;
2334 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002335 case Calibration::SizeCalibration::DEFAULT:
2336 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2337 break;
2338 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002339 touchMajor = 0;
2340 touchMinor = 0;
2341 toolMajor = 0;
2342 toolMinor = 0;
2343 size = 0;
2344 break;
2345 }
2346
2347 // Pressure
2348 float pressure;
2349 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002350 case Calibration::PressureCalibration::PHYSICAL:
2351 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002352 pressure = in.pressure * mPressureScale;
2353 break;
2354 default:
2355 pressure = in.isHovering ? 0 : 1;
2356 break;
2357 }
2358
2359 // Tilt and Orientation
2360 float tilt;
2361 float orientation;
2362 if (mHaveTilt) {
2363 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2364 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002365 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002366 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2367 } else {
2368 tilt = 0;
2369
2370 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002371 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002372 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002373 break;
Michael Wright227c5542020-07-02 18:30:52 +01002374 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002375 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2376 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2377 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002378 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002379 float confidence = hypotf(c1, c2);
2380 float scale = 1.0f + confidence / 16.0f;
2381 touchMajor *= scale;
2382 touchMinor /= scale;
2383 toolMajor *= scale;
2384 toolMinor /= scale;
2385 } else {
2386 orientation = 0;
2387 }
2388 break;
2389 }
2390 default:
2391 orientation = 0;
2392 }
2393 }
2394
2395 // Distance
2396 float distance;
2397 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002398 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002399 distance = in.distance * mDistanceScale;
2400 break;
2401 default:
2402 distance = 0;
2403 }
2404
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002405 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2406 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002407 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2408 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002409
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002410 // Write output coords.
2411 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2412 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002413 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2414 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002415 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2416 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2417 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2418 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2419 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2420 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2421 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002422 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2423 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002424
Chris Ye364fdb52020-08-05 15:07:56 -07002425 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002426 uint32_t id = in.id;
2427 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2428 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2429 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002430 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2431 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002432 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2433 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2434 }
2435
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002436 // Write output properties.
2437 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002438 properties.clear();
2439 properties.id = id;
2440 properties.toolType = in.toolType;
2441
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002442 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002443 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002444 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002445 }
2446}
2447
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002448std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2449 uint32_t policyFlags,
2450 PointerUsage pointerUsage) {
2451 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002452 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002453 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002454 mPointerUsage = pointerUsage;
2455 }
2456
2457 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002458 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002459 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002460 break;
Michael Wright227c5542020-07-02 18:30:52 +01002461 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002462 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002463 break;
Michael Wright227c5542020-07-02 18:30:52 +01002464 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002465 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002466 break;
Michael Wright227c5542020-07-02 18:30:52 +01002467 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002468 break;
2469 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002470 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002471}
2472
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002473std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2474 uint32_t policyFlags) {
2475 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002476 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002477 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002478 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002479 break;
Michael Wright227c5542020-07-02 18:30:52 +01002480 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002481 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002482 break;
Michael Wright227c5542020-07-02 18:30:52 +01002483 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002484 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002485 break;
Michael Wright227c5542020-07-02 18:30:52 +01002486 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002487 break;
2488 }
2489
Michael Wright227c5542020-07-02 18:30:52 +01002490 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002491 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002492}
2493
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002494std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2495 uint32_t policyFlags,
2496 bool isTimeout) {
2497 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002498 // Update current gesture coordinates.
2499 bool cancelPreviousGesture, finishPreviousGesture;
2500 bool sendEvents =
2501 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2502 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002503 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002504 }
2505 if (finishPreviousGesture) {
2506 cancelPreviousGesture = false;
2507 }
2508
2509 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002510 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002511 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002512 if (finishPreviousGesture || cancelPreviousGesture) {
2513 mPointerController->clearSpots();
2514 }
2515
Michael Wright227c5542020-07-02 18:30:52 +01002516 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002517 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2518 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002519 mPointerGesture.currentGestureIdBits,
2520 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002521 }
2522 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002523 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002524 }
2525
2526 // Show or hide the pointer if needed.
2527 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002528 case PointerGesture::Mode::NEUTRAL:
2529 case PointerGesture::Mode::QUIET:
2530 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2531 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002532 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002533 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002534 }
2535 break;
Michael Wright227c5542020-07-02 18:30:52 +01002536 case PointerGesture::Mode::TAP:
2537 case PointerGesture::Mode::TAP_DRAG:
2538 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2539 case PointerGesture::Mode::HOVER:
2540 case PointerGesture::Mode::PRESS:
2541 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002542 // Unfade the pointer when the current gesture manipulates the
2543 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002544 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002545 break;
Michael Wright227c5542020-07-02 18:30:52 +01002546 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002547 // Fade the pointer when the current gesture manipulates a different
2548 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002549 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002550 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002551 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002552 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002553 }
2554 break;
2555 }
2556
2557 // Send events!
2558 int32_t metaState = getContext()->getGlobalMetaState();
2559 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002560 const MotionClassification classification =
2561 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2562 ? MotionClassification::TWO_FINGER_SWIPE
2563 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002564
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002565 uint32_t flags = 0;
2566
2567 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2568 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2569 }
2570
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002571 // Update last coordinates of pointers that have moved so that we observe the new
2572 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002573 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2574 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2575 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2576 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2577 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2578 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002579 bool moveNeeded = false;
2580 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2581 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2582 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2583 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2584 mPointerGesture.lastGestureIdBits.value);
2585 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2586 mPointerGesture.currentGestureCoords,
2587 mPointerGesture.currentGestureIdToIndex,
2588 mPointerGesture.lastGestureProperties,
2589 mPointerGesture.lastGestureCoords,
2590 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2591 if (buttonState != mLastCookedState.buttonState) {
2592 moveNeeded = true;
2593 }
2594 }
2595
2596 // Send motion events for all pointers that went up or were canceled.
2597 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2598 if (!dispatchedGestureIdBits.isEmpty()) {
2599 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002600 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002601 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002602 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002603 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2604 mPointerGesture.lastGestureProperties,
2605 mPointerGesture.lastGestureCoords,
2606 mPointerGesture.lastGestureIdToIndex,
2607 dispatchedGestureIdBits, -1, 0, 0,
2608 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002609
2610 dispatchedGestureIdBits.clear();
2611 } else {
2612 BitSet32 upGestureIdBits;
2613 if (finishPreviousGesture) {
2614 upGestureIdBits = dispatchedGestureIdBits;
2615 } else {
2616 upGestureIdBits.value =
2617 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2618 }
2619 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002620 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2621 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2622 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2623 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2624 readTime);
2625 }
2626 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002627 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2628 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2629 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2630 mPointerGesture.lastGestureProperties,
2631 mPointerGesture.lastGestureCoords,
2632 mPointerGesture.lastGestureIdToIndex,
2633 dispatchedGestureIdBits, id, 0, 0,
2634 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002635
2636 dispatchedGestureIdBits.clearBit(id);
2637 }
2638 }
2639 }
2640
2641 // Send motion events for all pointers that moved.
2642 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002643 out.push_back(
2644 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2645 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2646 mPointerGesture.currentGestureProperties,
2647 mPointerGesture.currentGestureCoords,
2648 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2649 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002650 }
2651
2652 // Send motion events for all pointers that went down.
2653 if (down) {
2654 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2655 ~dispatchedGestureIdBits.value);
2656 while (!downGestureIdBits.isEmpty()) {
2657 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2658 dispatchedGestureIdBits.markBit(id);
2659
2660 if (dispatchedGestureIdBits.count() == 1) {
2661 mPointerGesture.downTime = when;
2662 }
2663
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002664 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2665 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2666 buttonState, 0, mPointerGesture.currentGestureProperties,
2667 mPointerGesture.currentGestureCoords,
2668 mPointerGesture.currentGestureIdToIndex,
2669 dispatchedGestureIdBits, id, 0, 0,
2670 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002671 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2672 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2673 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2674 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2675 readTime);
2676 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002677 }
2678 }
2679
2680 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002681 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002682 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2683 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2684 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2685 mPointerGesture.currentGestureProperties,
2686 mPointerGesture.currentGestureCoords,
2687 mPointerGesture.currentGestureIdToIndex,
2688 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2689 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002690 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2691 // Synthesize a hover move event after all pointers go up to indicate that
2692 // the pointer is hovering again even if the user is not currently touching
2693 // the touch pad. This ensures that a view will receive a fresh hover enter
2694 // event after a tap.
Prabir Pradhan2719e822023-02-28 17:39:36 +00002695 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002696
2697 PointerProperties pointerProperties;
2698 pointerProperties.clear();
2699 pointerProperties.id = 0;
2700 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2701
2702 PointerCoords pointerCoords;
2703 pointerCoords.clear();
2704 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2705 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2706
2707 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002708 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2709 mSource, displayId, policyFlags,
2710 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2711 buttonState, MotionClassification::NONE,
2712 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2713 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2714 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002715 }
2716
2717 // Update state.
2718 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2719 if (!down) {
2720 mPointerGesture.lastGestureIdBits.clear();
2721 } else {
2722 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2723 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2724 uint32_t id = idBits.clearFirstMarkedBit();
2725 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2726 mPointerGesture.lastGestureProperties[index].copyFrom(
2727 mPointerGesture.currentGestureProperties[index]);
2728 mPointerGesture.lastGestureCoords[index].copyFrom(
2729 mPointerGesture.currentGestureCoords[index]);
2730 mPointerGesture.lastGestureIdToIndex[id] = index;
2731 }
2732 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002733 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002734}
2735
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002736std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2737 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002738 const MotionClassification classification =
2739 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2740 ? MotionClassification::TWO_FINGER_SWIPE
2741 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002742 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002743 // Cancel previously dispatches pointers.
2744 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2745 int32_t metaState = getContext()->getGlobalMetaState();
2746 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002747 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002748 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2749 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002750 mPointerGesture.lastGestureProperties,
2751 mPointerGesture.lastGestureCoords,
2752 mPointerGesture.lastGestureIdToIndex,
2753 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2754 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002755 }
2756
2757 // Reset the current pointer gesture.
2758 mPointerGesture.reset();
2759 mPointerVelocityControl.reset();
2760
2761 // Remove any current spots.
2762 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002763 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002764 mPointerController->clearSpots();
2765 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002766 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002767}
2768
2769bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2770 bool* outFinishPreviousGesture, bool isTimeout) {
2771 *outCancelPreviousGesture = false;
2772 *outFinishPreviousGesture = false;
2773
2774 // Handle TAP timeout.
2775 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002776 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002777
Michael Wright227c5542020-07-02 18:30:52 +01002778 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002779 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2780 // The tap/drag timeout has not yet expired.
2781 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2782 mConfig.pointerGestureTapDragInterval);
2783 } else {
2784 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002785 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002786 *outFinishPreviousGesture = true;
2787
2788 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002789 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002790 mPointerGesture.currentGestureIdBits.clear();
2791
2792 mPointerVelocityControl.reset();
2793 return true;
2794 }
2795 }
2796
2797 // We did not handle this timeout.
2798 return false;
2799 }
2800
2801 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2802 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2803
2804 // Update the velocity tracker.
2805 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002806 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002807 uint32_t id = idBits.clearFirstMarkedBit();
2808 const RawPointerData::Pointer& pointer =
2809 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002810 const float x = pointer.x * mPointerXMovementScale;
2811 const float y = pointer.y * mPointerYMovementScale;
2812 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2813 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002814 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002815 }
2816
2817 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2818 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002819 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2820 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2821 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002822 mPointerGesture.resetTap();
2823 }
2824
2825 // Pick a new active touch id if needed.
2826 // Choose an arbitrary pointer that just went down, if there is one.
2827 // Otherwise choose an arbitrary remaining pointer.
2828 // This guarantees we always have an active touch id when there is at least one pointer.
2829 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002830 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002831 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002832 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002833 mPointerGesture.firstTouchTime = when;
2834 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002835 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2836 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2837 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2838 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002839 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002840 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002841
2842 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002843 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002844 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002845 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2846 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2847 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002848 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002849 *outFinishPreviousGesture = true;
2850 }
2851
2852 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002853 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002854 mPointerGesture.currentGestureIdBits.clear();
2855
2856 mPointerVelocityControl.reset();
2857 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2858 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2859 // The pointer follows the active touch point.
2860 // Emit DOWN, MOVE, UP events at the pointer location.
2861 //
2862 // Only the active touch matters; other fingers are ignored. This policy helps
2863 // to handle the case where the user places a second finger on the touch pad
2864 // to apply the necessary force to depress an integrated button below the surface.
2865 // We don't want the second finger to be delivered to applications.
2866 //
2867 // For this to work well, we need to make sure to track the pointer that is really
2868 // active. If the user first puts one finger down to click then adds another
2869 // finger to drag then the active pointer should switch to the finger that is
2870 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002871 ALOGD_IF(DEBUG_GESTURES,
2872 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2873 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002874 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002875 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002876 *outFinishPreviousGesture = true;
2877 mPointerGesture.activeGestureId = 0;
2878 }
2879
2880 // Switch pointers if needed.
2881 // Find the fastest pointer and follow it.
2882 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002883 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002884 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002885 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002886 ALOGD_IF(DEBUG_GESTURES,
2887 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2888 "bestSpeed=%0.3f",
2889 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002890 }
2891 }
2892
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002893 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002894 // When using spots, the click will occur at the position of the anchor
2895 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002896 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002897 } else {
2898 mPointerVelocityControl.reset();
2899 }
2900
Prabir Pradhan2719e822023-02-28 17:39:36 +00002901 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002902
Michael Wright227c5542020-07-02 18:30:52 +01002903 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002904 mPointerGesture.currentGestureIdBits.clear();
2905 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2906 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2907 mPointerGesture.currentGestureProperties[0].clear();
2908 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2909 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2910 mPointerGesture.currentGestureCoords[0].clear();
2911 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2912 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2913 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2914 } else if (currentFingerCount == 0) {
2915 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002916 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002917 *outFinishPreviousGesture = true;
2918 }
2919
2920 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2921 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2922 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002923 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2924 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002925 lastFingerCount == 1) {
2926 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00002927 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002928 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2929 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002930 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002931
2932 mPointerGesture.tapUpTime = when;
2933 getContext()->requestTimeoutAtTime(when +
2934 mConfig.pointerGestureTapDragInterval);
2935
2936 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002937 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002938 mPointerGesture.currentGestureIdBits.clear();
2939 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2940 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2941 mPointerGesture.currentGestureProperties[0].clear();
2942 mPointerGesture.currentGestureProperties[0].id =
2943 mPointerGesture.activeGestureId;
2944 mPointerGesture.currentGestureProperties[0].toolType =
2945 AMOTION_EVENT_TOOL_TYPE_FINGER;
2946 mPointerGesture.currentGestureCoords[0].clear();
2947 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2948 mPointerGesture.tapX);
2949 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2950 mPointerGesture.tapY);
2951 mPointerGesture.currentGestureCoords[0]
2952 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2953
2954 tapped = true;
2955 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002956 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2957 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002958 }
2959 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002960 if (DEBUG_GESTURES) {
2961 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2962 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2963 (when - mPointerGesture.tapDownTime) * 0.000001f);
2964 } else {
2965 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2966 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002967 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002968 }
2969 }
2970
2971 mPointerVelocityControl.reset();
2972
2973 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002974 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002975 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002976 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002977 mPointerGesture.currentGestureIdBits.clear();
2978 }
2979 } else if (currentFingerCount == 1) {
2980 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2981 // The pointer follows the active touch point.
2982 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2983 // When in TAP_DRAG, emit MOVE events at the pointer location.
2984 ALOG_ASSERT(activeTouchId >= 0);
2985
Michael Wright227c5542020-07-02 18:30:52 +01002986 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2987 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002988 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00002989 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002990 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2991 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002992 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002993 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002994 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2995 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002996 }
2997 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002998 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2999 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003000 }
Michael Wright227c5542020-07-02 18:30:52 +01003001 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3002 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003003 }
3004
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003005 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003006 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003007 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003008 } else {
3009 mPointerVelocityControl.reset();
3010 }
3011
3012 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003013 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003014 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003015 down = true;
3016 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003017 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003018 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003019 *outFinishPreviousGesture = true;
3020 }
3021 mPointerGesture.activeGestureId = 0;
3022 down = false;
3023 }
3024
Prabir Pradhan2719e822023-02-28 17:39:36 +00003025 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003026
3027 mPointerGesture.currentGestureIdBits.clear();
3028 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3029 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3030 mPointerGesture.currentGestureProperties[0].clear();
3031 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3032 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3033 mPointerGesture.currentGestureCoords[0].clear();
3034 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3035 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3036 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3037 down ? 1.0f : 0.0f);
3038
3039 if (lastFingerCount == 0 && currentFingerCount != 0) {
3040 mPointerGesture.resetTap();
3041 mPointerGesture.tapDownTime = when;
3042 mPointerGesture.tapX = x;
3043 mPointerGesture.tapY = y;
3044 }
3045 } else {
3046 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003047 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003048 }
3049
3050 mPointerController->setButtonState(mCurrentRawState.buttonState);
3051
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003052 if (DEBUG_GESTURES) {
3053 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3054 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3055 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3056 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3057 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3058 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3059 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3060 uint32_t id = idBits.clearFirstMarkedBit();
3061 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3062 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3063 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3064 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3065 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3066 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3067 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3068 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3069 }
3070 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3071 uint32_t id = idBits.clearFirstMarkedBit();
3072 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3073 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3074 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3075 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3076 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3077 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3078 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3079 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3080 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003081 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003082 return true;
3083}
3084
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003085bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3086 if (mPointerGesture.activeTouchId < 0) {
3087 mPointerGesture.resetQuietTime();
3088 return false;
3089 }
3090
3091 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3092 return true;
3093 }
3094
3095 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3096 bool isQuietTime = false;
3097 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3098 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3099 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3100 currentFingerCount < 2) {
3101 // Enter quiet time when exiting swipe or freeform state.
3102 // This is to prevent accidentally entering the hover state and flinging the
3103 // pointer when finishing a swipe and there is still one pointer left onscreen.
3104 isQuietTime = true;
3105 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3106 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3107 // Enter quiet time when releasing the button and there are still two or more
3108 // fingers down. This may indicate that one finger was used to press the button
3109 // but it has not gone up yet.
3110 isQuietTime = true;
3111 }
3112 if (isQuietTime) {
3113 mPointerGesture.quietTime = when;
3114 }
3115 return isQuietTime;
3116}
3117
3118std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3119 int32_t bestId = -1;
3120 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3121 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3122 uint32_t id = idBits.clearFirstMarkedBit();
3123 std::optional<float> vx =
3124 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3125 std::optional<float> vy =
3126 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3127 if (vx && vy) {
3128 float speed = hypotf(*vx, *vy);
3129 if (speed > bestSpeed) {
3130 bestId = id;
3131 bestSpeed = speed;
3132 }
3133 }
3134 }
3135 return std::make_pair(bestId, bestSpeed);
3136}
3137
3138void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3139 bool* finishPreviousGesture) {
3140 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3141 // to move before deciding what to do.
3142 //
3143 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3144 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3145 // just a press or long-press at the pointer location.
3146 //
3147 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3148 // pointer location.
3149 //
3150 // When the two fingers move enough or when additional fingers are added, we make a decision to
3151 // transition into SWIPE or FREEFORM mode accordingly.
3152 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3153 ALOG_ASSERT(activeTouchId >= 0);
3154
3155 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3156 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3157 bool settled =
3158 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3159 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3160 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3161 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3162 *finishPreviousGesture = true;
3163 } else if (!settled && currentFingerCount > lastFingerCount) {
3164 // Additional pointers have gone down but not yet settled.
3165 // Reset the gesture.
3166 ALOGD_IF(DEBUG_GESTURES,
3167 "Gestures: Resetting gesture since additional pointers went down for "
3168 "MULTITOUCH, settle time remaining %0.3fms",
3169 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3170 when) * 0.000001f);
3171 *cancelPreviousGesture = true;
3172 } else {
3173 // Continue previous gesture.
3174 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3175 }
3176
3177 if (*finishPreviousGesture || *cancelPreviousGesture) {
3178 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3179 mPointerGesture.activeGestureId = 0;
3180 mPointerGesture.referenceIdBits.clear();
3181 mPointerVelocityControl.reset();
3182
3183 // Use the centroid and pointer location as the reference points for the gesture.
3184 ALOGD_IF(DEBUG_GESTURES,
3185 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3186 "%0.3fms",
3187 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3188 when) * 0.000001f);
3189 mCurrentRawState.rawPointerData
3190 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3191 &mPointerGesture.referenceTouchY);
Prabir Pradhan2719e822023-02-28 17:39:36 +00003192 std::tie(mPointerGesture.referenceGestureX, mPointerGesture.referenceGestureY) =
3193 mPointerController->getPosition();
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003194 }
3195
3196 // Clear the reference deltas for fingers not yet included in the reference calculation.
3197 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3198 ~mPointerGesture.referenceIdBits.value);
3199 !idBits.isEmpty();) {
3200 uint32_t id = idBits.clearFirstMarkedBit();
3201 mPointerGesture.referenceDeltas[id].dx = 0;
3202 mPointerGesture.referenceDeltas[id].dy = 0;
3203 }
3204 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3205
3206 // Add delta for all fingers and calculate a common movement delta.
3207 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3208 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3209 mCurrentCookedState.fingerIdBits.value);
3210 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3211 bool first = (idBits == commonIdBits);
3212 uint32_t id = idBits.clearFirstMarkedBit();
3213 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3214 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3215 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3216 delta.dx += cpd.x - lpd.x;
3217 delta.dy += cpd.y - lpd.y;
3218
3219 if (first) {
3220 commonDeltaRawX = delta.dx;
3221 commonDeltaRawY = delta.dy;
3222 } else {
3223 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3224 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3225 }
3226 }
3227
3228 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3229 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3230 float dist[MAX_POINTER_ID + 1];
3231 int32_t distOverThreshold = 0;
3232 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3233 uint32_t id = idBits.clearFirstMarkedBit();
3234 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3235 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3236 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3237 distOverThreshold += 1;
3238 }
3239 }
3240
3241 // Only transition when at least two pointers have moved further than
3242 // the minimum distance threshold.
3243 if (distOverThreshold >= 2) {
3244 if (currentFingerCount > 2) {
3245 // There are more than two pointers, switch to FREEFORM.
3246 ALOGD_IF(DEBUG_GESTURES,
3247 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3248 currentFingerCount);
3249 *cancelPreviousGesture = true;
3250 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3251 } else {
3252 // There are exactly two pointers.
3253 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3254 uint32_t id1 = idBits.clearFirstMarkedBit();
3255 uint32_t id2 = idBits.firstMarkedBit();
3256 const RawPointerData::Pointer& p1 =
3257 mCurrentRawState.rawPointerData.pointerForId(id1);
3258 const RawPointerData::Pointer& p2 =
3259 mCurrentRawState.rawPointerData.pointerForId(id2);
3260 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3261 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3262 // There are two pointers but they are too far apart for a SWIPE,
3263 // switch to FREEFORM.
3264 ALOGD_IF(DEBUG_GESTURES,
3265 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3266 mutualDistance, mPointerGestureMaxSwipeWidth);
3267 *cancelPreviousGesture = true;
3268 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3269 } else {
3270 // There are two pointers. Wait for both pointers to start moving
3271 // before deciding whether this is a SWIPE or FREEFORM gesture.
3272 float dist1 = dist[id1];
3273 float dist2 = dist[id2];
3274 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3275 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3276 // Calculate the dot product of the displacement vectors.
3277 // When the vectors are oriented in approximately the same direction,
3278 // the angle betweeen them is near zero and the cosine of the angle
3279 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3280 // mag(v2).
3281 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3282 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3283 float dx1 = delta1.dx * mPointerXZoomScale;
3284 float dy1 = delta1.dy * mPointerYZoomScale;
3285 float dx2 = delta2.dx * mPointerXZoomScale;
3286 float dy2 = delta2.dy * mPointerYZoomScale;
3287 float dot = dx1 * dx2 + dy1 * dy2;
3288 float cosine = dot / (dist1 * dist2); // denominator always > 0
3289 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3290 // Pointers are moving in the same direction. Switch to SWIPE.
3291 ALOGD_IF(DEBUG_GESTURES,
3292 "Gestures: PRESS transitioned to SWIPE, "
3293 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3294 "cosine %0.3f >= %0.3f",
3295 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3296 mConfig.pointerGestureMultitouchMinDistance, cosine,
3297 mConfig.pointerGestureSwipeTransitionAngleCosine);
3298 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3299 } else {
3300 // Pointers are moving in different directions. Switch to FREEFORM.
3301 ALOGD_IF(DEBUG_GESTURES,
3302 "Gestures: PRESS transitioned to FREEFORM, "
3303 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3304 "cosine %0.3f < %0.3f",
3305 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3306 mConfig.pointerGestureMultitouchMinDistance, cosine,
3307 mConfig.pointerGestureSwipeTransitionAngleCosine);
3308 *cancelPreviousGesture = true;
3309 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3310 }
3311 }
3312 }
3313 }
3314 }
3315 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3316 // Switch from SWIPE to FREEFORM if additional pointers go down.
3317 // Cancel previous gesture.
3318 if (currentFingerCount > 2) {
3319 ALOGD_IF(DEBUG_GESTURES,
3320 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3321 currentFingerCount);
3322 *cancelPreviousGesture = true;
3323 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3324 }
3325 }
3326
3327 // Move the reference points based on the overall group motion of the fingers
3328 // except in PRESS mode while waiting for a transition to occur.
3329 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3330 (commonDeltaRawX || commonDeltaRawY)) {
3331 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3332 uint32_t id = idBits.clearFirstMarkedBit();
3333 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3334 delta.dx = 0;
3335 delta.dy = 0;
3336 }
3337
3338 mPointerGesture.referenceTouchX += commonDeltaRawX;
3339 mPointerGesture.referenceTouchY += commonDeltaRawY;
3340
3341 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3342 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3343
3344 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3345 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3346
3347 mPointerGesture.referenceGestureX += commonDeltaX;
3348 mPointerGesture.referenceGestureY += commonDeltaY;
3349 }
3350
3351 // Report gestures.
3352 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3353 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3354 // PRESS or SWIPE mode.
3355 ALOGD_IF(DEBUG_GESTURES,
3356 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3357 "currentTouchPointerCount=%d",
3358 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3359 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3360
3361 mPointerGesture.currentGestureIdBits.clear();
3362 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3363 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3364 mPointerGesture.currentGestureProperties[0].clear();
3365 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3366 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3367 mPointerGesture.currentGestureCoords[0].clear();
3368 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3369 mPointerGesture.referenceGestureX);
3370 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3371 mPointerGesture.referenceGestureY);
3372 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3373 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3374 float xOffset = static_cast<float>(commonDeltaRawX) /
3375 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3376 float yOffset = static_cast<float>(commonDeltaRawY) /
3377 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3378 mPointerGesture.currentGestureCoords[0]
3379 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3380 mPointerGesture.currentGestureCoords[0]
3381 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3382 }
3383 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3384 // FREEFORM mode.
3385 ALOGD_IF(DEBUG_GESTURES,
3386 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3387 "currentTouchPointerCount=%d",
3388 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3389 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3390
3391 mPointerGesture.currentGestureIdBits.clear();
3392
3393 BitSet32 mappedTouchIdBits;
3394 BitSet32 usedGestureIdBits;
3395 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3396 // Initially, assign the active gesture id to the active touch point
3397 // if there is one. No other touch id bits are mapped yet.
3398 if (!*cancelPreviousGesture) {
3399 mappedTouchIdBits.markBit(activeTouchId);
3400 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3401 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3402 mPointerGesture.activeGestureId;
3403 } else {
3404 mPointerGesture.activeGestureId = -1;
3405 }
3406 } else {
3407 // Otherwise, assume we mapped all touches from the previous frame.
3408 // Reuse all mappings that are still applicable.
3409 mappedTouchIdBits.value =
3410 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3411 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3412
3413 // Check whether we need to choose a new active gesture id because the
3414 // current went went up.
3415 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3416 ~mCurrentCookedState.fingerIdBits.value);
3417 !upTouchIdBits.isEmpty();) {
3418 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3419 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3420 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3421 mPointerGesture.activeGestureId = -1;
3422 break;
3423 }
3424 }
3425 }
3426
3427 ALOGD_IF(DEBUG_GESTURES,
3428 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3429 "activeGestureId=%d",
3430 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3431
3432 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3433 for (uint32_t i = 0; i < currentFingerCount; i++) {
3434 uint32_t touchId = idBits.clearFirstMarkedBit();
3435 uint32_t gestureId;
3436 if (!mappedTouchIdBits.hasBit(touchId)) {
3437 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3438 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3439 ALOGD_IF(DEBUG_GESTURES,
3440 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3441 gestureId);
3442 } else {
3443 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3444 ALOGD_IF(DEBUG_GESTURES,
3445 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3446 touchId, gestureId);
3447 }
3448 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3449 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3450
3451 const RawPointerData::Pointer& pointer =
3452 mCurrentRawState.rawPointerData.pointerForId(touchId);
3453 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3454 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3455 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3456
3457 mPointerGesture.currentGestureProperties[i].clear();
3458 mPointerGesture.currentGestureProperties[i].id = gestureId;
3459 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3460 mPointerGesture.currentGestureCoords[i].clear();
3461 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3462 mPointerGesture.referenceGestureX +
3463 deltaX);
3464 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3465 mPointerGesture.referenceGestureY +
3466 deltaY);
3467 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3468 }
3469
3470 if (mPointerGesture.activeGestureId < 0) {
3471 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3472 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3473 mPointerGesture.activeGestureId);
3474 }
3475 }
3476}
3477
Harry Cutts714d1ad2022-08-24 16:36:43 +00003478void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3479 const RawPointerData::Pointer& currentPointer =
3480 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3481 const RawPointerData::Pointer& lastPointer =
3482 mLastRawState.rawPointerData.pointerForId(pointerId);
3483 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3484 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3485
3486 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3487 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3488
3489 mPointerController->move(deltaX, deltaY);
3490}
3491
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003492std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3493 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003494 mPointerSimple.currentCoords.clear();
3495 mPointerSimple.currentProperties.clear();
3496
3497 bool down, hovering;
3498 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3499 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3500 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003501 mPointerController
3502 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3503 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003504
3505 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3506 down = !hovering;
3507
Prabir Pradhan2719e822023-02-28 17:39:36 +00003508 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003509 mPointerSimple.currentCoords.copyFrom(
3510 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3511 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3512 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3513 mPointerSimple.currentProperties.id = 0;
3514 mPointerSimple.currentProperties.toolType =
3515 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3516 } else {
3517 down = false;
3518 hovering = false;
3519 }
3520
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003521 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003522}
3523
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003524std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3525 uint32_t policyFlags) {
3526 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003527}
3528
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003529std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3530 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003531 mPointerSimple.currentCoords.clear();
3532 mPointerSimple.currentProperties.clear();
3533
3534 bool down, hovering;
3535 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3536 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003537 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003538 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003539 } else {
3540 mPointerVelocityControl.reset();
3541 }
3542
3543 down = isPointerDown(mCurrentRawState.buttonState);
3544 hovering = !down;
3545
Prabir Pradhan2719e822023-02-28 17:39:36 +00003546 const auto [x, y] = mPointerController->getPosition();
3547 const uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003548 mPointerSimple.currentCoords.copyFrom(
3549 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3550 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3551 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3552 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3553 hovering ? 0.0f : 1.0f);
3554 mPointerSimple.currentProperties.id = 0;
3555 mPointerSimple.currentProperties.toolType =
3556 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3557 } else {
3558 mPointerVelocityControl.reset();
3559
3560 down = false;
3561 hovering = false;
3562 }
3563
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003564 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003565}
3566
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003567std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3568 uint32_t policyFlags) {
3569 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003570
3571 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003572
3573 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003574}
3575
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003576std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3577 uint32_t policyFlags, bool down,
3578 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003579 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3580 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003581 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003582 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003583
3584 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003585 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003586 mPointerController->clearSpots();
3587 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003588 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003589 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003590 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003591 }
Garfield Tan9514d782020-11-10 16:37:23 -08003592 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003593
Prabir Pradhan2719e822023-02-28 17:39:36 +00003594 const auto [xCursorPosition, yCursorPosition] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003595
3596 if (mPointerSimple.down && !down) {
3597 mPointerSimple.down = false;
3598
3599 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003600 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3601 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3602 0, metaState, mLastRawState.buttonState,
3603 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3604 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3605 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3606 yCursorPosition, mPointerSimple.downTime,
3607 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003608 }
3609
3610 if (mPointerSimple.hovering && !hovering) {
3611 mPointerSimple.hovering = false;
3612
3613 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003614 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3615 mSource, displayId, policyFlags,
3616 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3617 mLastRawState.buttonState, MotionClassification::NONE,
3618 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3619 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3620 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3621 yCursorPosition, mPointerSimple.downTime,
3622 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003623 }
3624
3625 if (down) {
3626 if (!mPointerSimple.down) {
3627 mPointerSimple.down = true;
3628 mPointerSimple.downTime = when;
3629
3630 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003631 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3632 mSource, displayId, policyFlags,
3633 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3634 mCurrentRawState.buttonState, MotionClassification::NONE,
3635 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3636 &mPointerSimple.currentProperties,
3637 &mPointerSimple.currentCoords, mOrientedXPrecision,
3638 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3639 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003640 }
3641
3642 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003643 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3644 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3645 0, 0, metaState, mCurrentRawState.buttonState,
3646 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3647 &mPointerSimple.currentProperties,
3648 &mPointerSimple.currentCoords, mOrientedXPrecision,
3649 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3650 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003651 }
3652
3653 if (hovering) {
3654 if (!mPointerSimple.hovering) {
3655 mPointerSimple.hovering = true;
3656
3657 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003658 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3659 mSource, displayId, policyFlags,
3660 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3661 mCurrentRawState.buttonState, MotionClassification::NONE,
3662 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3663 &mPointerSimple.currentProperties,
3664 &mPointerSimple.currentCoords, mOrientedXPrecision,
3665 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3666 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003667 }
3668
3669 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003670 out.push_back(
3671 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3672 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3673 metaState, mCurrentRawState.buttonState,
3674 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3675 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3676 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3677 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003678 }
3679
3680 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3681 float vscroll = mCurrentRawState.rawVScroll;
3682 float hscroll = mCurrentRawState.rawHScroll;
3683 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3684 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3685
3686 // Send scroll.
3687 PointerCoords pointerCoords;
3688 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3689 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3690 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3691
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003692 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3693 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3694 0, 0, metaState, mCurrentRawState.buttonState,
3695 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3696 &mPointerSimple.currentProperties, &pointerCoords,
3697 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3698 yCursorPosition, mPointerSimple.downTime,
3699 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003700 }
3701
3702 // Save state.
3703 if (down || hovering) {
3704 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3705 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003706 mPointerSimple.displayId = displayId;
3707 mPointerSimple.source = mSource;
3708 mPointerSimple.lastCursorX = xCursorPosition;
3709 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003710 } else {
3711 mPointerSimple.reset();
3712 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003713 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003714}
3715
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003716std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3717 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003718 std::list<NotifyArgs> out;
3719 if (mPointerSimple.down || mPointerSimple.hovering) {
3720 int32_t metaState = getContext()->getGlobalMetaState();
3721 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3722 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3723 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3724 metaState, mLastRawState.buttonState,
3725 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3726 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3727 mOrientedXPrecision, mOrientedYPrecision,
3728 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3729 mPointerSimple.downTime,
3730 /* videoFrames */ {}));
3731 if (mPointerController != nullptr) {
3732 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3733 }
3734 }
3735 mPointerSimple.reset();
3736 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003737}
3738
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003739static bool isStylusEvent(uint32_t source, int32_t action, const PointerProperties* properties) {
3740 if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
3741 return false;
3742 }
3743 const auto actionIndex = action >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3744 return isStylusToolType(properties[actionIndex].toolType);
3745}
3746
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003747NotifyMotionArgs TouchInputMapper::dispatchMotion(
3748 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3749 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003750 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3751 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003752 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003753 PointerCoords pointerCoords[MAX_POINTERS];
3754 PointerProperties pointerProperties[MAX_POINTERS];
3755 uint32_t pointerCount = 0;
3756 while (!idBits.isEmpty()) {
3757 uint32_t id = idBits.clearFirstMarkedBit();
3758 uint32_t index = idToIndex[id];
3759 pointerProperties[pointerCount].copyFrom(properties[index]);
3760 pointerCoords[pointerCount].copyFrom(coords[index]);
3761
3762 if (changedId >= 0 && id == uint32_t(changedId)) {
3763 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3764 }
3765
3766 pointerCount += 1;
3767 }
3768
3769 ALOG_ASSERT(pointerCount != 0);
3770
3771 if (changedId >= 0 && pointerCount == 1) {
3772 // Replace initial down and final up action.
3773 // We can compare the action without masking off the changed pointer index
3774 // because we know the index is 0.
3775 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3776 action = AMOTION_EVENT_ACTION_DOWN;
3777 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003778 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3779 action = AMOTION_EVENT_ACTION_CANCEL;
3780 } else {
3781 action = AMOTION_EVENT_ACTION_UP;
3782 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003783 } else {
3784 // Can't happen.
3785 ALOG_ASSERT(false);
3786 }
3787 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003788
3789 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3790 const bool showDirectStylusPointer = mConfig.stylusPointerIconEnabled &&
3791 mDeviceMode == DeviceMode::DIRECT && isStylusEvent(source, action, pointerProperties) &&
Seunghwan Choi356026c2023-02-01 14:37:25 +09003792 mPointerController && displayId != ADISPLAY_ID_NONE &&
3793 displayId == mPointerController->getDisplayId();
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003794 if (showDirectStylusPointer) {
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003795 switch (action & AMOTION_EVENT_ACTION_MASK) {
3796 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3797 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3798 mPointerController->setPresentation(
Seunghwan Choi75789cd2023-01-13 20:31:59 +09003799 PointerControllerInterface::Presentation::STYLUS_HOVER);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003800 mPointerController
3801 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[0].getX(),
3802 mCurrentCookedState.cookedPointerData.pointerCoords[0]
3803 .getY());
3804 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3805 break;
3806 case AMOTION_EVENT_ACTION_HOVER_EXIT:
3807 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
3808 break;
3809 }
3810 }
3811
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003812 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3813 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003814 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003815 std::tie(xCursorPosition, yCursorPosition) = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003816 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003817 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003818 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003819 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003820 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003821 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3822 policyFlags, action, actionButton, flags, metaState, buttonState,
3823 classification, edgeFlags, pointerCount, pointerProperties,
3824 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3825 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003826}
3827
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003828std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3829 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003830 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3831 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003832 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003833}
3834
Prabir Pradhan1728b212021-10-19 16:00:03 -07003835bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003836 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003837 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003838 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003839}
3840
3841const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3842 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003843 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3844 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3845 "left=%d, top=%d, right=%d, bottom=%d",
3846 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3847 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003848
3849 if (virtualKey.isHit(x, y)) {
3850 return &virtualKey;
3851 }
3852 }
3853
3854 return nullptr;
3855}
3856
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003857void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3858 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3859 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003860
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003861 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003862
3863 if (currentPointerCount == 0) {
3864 // No pointers to assign.
3865 return;
3866 }
3867
3868 if (lastPointerCount == 0) {
3869 // All pointers are new.
3870 for (uint32_t i = 0; i < currentPointerCount; i++) {
3871 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003872 current.rawPointerData.pointers[i].id = id;
3873 current.rawPointerData.idToIndex[id] = i;
3874 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003875 }
3876 return;
3877 }
3878
3879 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003880 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003881 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003882 uint32_t id = last.rawPointerData.pointers[0].id;
3883 current.rawPointerData.pointers[0].id = id;
3884 current.rawPointerData.idToIndex[id] = 0;
3885 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003886 return;
3887 }
3888
3889 // General case.
3890 // We build a heap of squared euclidean distances between current and last pointers
3891 // associated with the current and last pointer indices. Then, we find the best
3892 // match (by distance) for each current pointer.
3893 // The pointers must have the same tool type but it is possible for them to
3894 // transition from hovering to touching or vice-versa while retaining the same id.
3895 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3896
3897 uint32_t heapSize = 0;
3898 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3899 currentPointerIndex++) {
3900 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3901 lastPointerIndex++) {
3902 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003903 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003904 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003905 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003906 if (currentPointer.toolType == lastPointer.toolType) {
3907 int64_t deltaX = currentPointer.x - lastPointer.x;
3908 int64_t deltaY = currentPointer.y - lastPointer.y;
3909
3910 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3911
3912 // Insert new element into the heap (sift up).
3913 heap[heapSize].currentPointerIndex = currentPointerIndex;
3914 heap[heapSize].lastPointerIndex = lastPointerIndex;
3915 heap[heapSize].distance = distance;
3916 heapSize += 1;
3917 }
3918 }
3919 }
3920
3921 // Heapify
3922 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3923 startIndex -= 1;
3924 for (uint32_t parentIndex = startIndex;;) {
3925 uint32_t childIndex = parentIndex * 2 + 1;
3926 if (childIndex >= heapSize) {
3927 break;
3928 }
3929
3930 if (childIndex + 1 < heapSize &&
3931 heap[childIndex + 1].distance < heap[childIndex].distance) {
3932 childIndex += 1;
3933 }
3934
3935 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3936 break;
3937 }
3938
3939 swap(heap[parentIndex], heap[childIndex]);
3940 parentIndex = childIndex;
3941 }
3942 }
3943
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003944 if (DEBUG_POINTER_ASSIGNMENT) {
3945 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3946 for (size_t i = 0; i < heapSize; i++) {
3947 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3948 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3949 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003950 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003951
3952 // Pull matches out by increasing order of distance.
3953 // To avoid reassigning pointers that have already been matched, the loop keeps track
3954 // of which last and current pointers have been matched using the matchedXXXBits variables.
3955 // It also tracks the used pointer id bits.
3956 BitSet32 matchedLastBits(0);
3957 BitSet32 matchedCurrentBits(0);
3958 BitSet32 usedIdBits(0);
3959 bool first = true;
3960 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3961 while (heapSize > 0) {
3962 if (first) {
3963 // The first time through the loop, we just consume the root element of
3964 // the heap (the one with smallest distance).
3965 first = false;
3966 } else {
3967 // Previous iterations consumed the root element of the heap.
3968 // Pop root element off of the heap (sift down).
3969 heap[0] = heap[heapSize];
3970 for (uint32_t parentIndex = 0;;) {
3971 uint32_t childIndex = parentIndex * 2 + 1;
3972 if (childIndex >= heapSize) {
3973 break;
3974 }
3975
3976 if (childIndex + 1 < heapSize &&
3977 heap[childIndex + 1].distance < heap[childIndex].distance) {
3978 childIndex += 1;
3979 }
3980
3981 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3982 break;
3983 }
3984
3985 swap(heap[parentIndex], heap[childIndex]);
3986 parentIndex = childIndex;
3987 }
3988
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003989 if (DEBUG_POINTER_ASSIGNMENT) {
3990 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3991 for (size_t j = 0; j < heapSize; j++) {
3992 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3993 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3994 heap[j].distance);
3995 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003996 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003997 }
3998
3999 heapSize -= 1;
4000
4001 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4002 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4003
4004 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4005 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4006
4007 matchedCurrentBits.markBit(currentPointerIndex);
4008 matchedLastBits.markBit(lastPointerIndex);
4009
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004010 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4011 current.rawPointerData.pointers[currentPointerIndex].id = id;
4012 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4013 current.rawPointerData.markIdBit(id,
4014 current.rawPointerData.isHovering(
4015 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004016 usedIdBits.markBit(id);
4017
Harry Cutts45483602022-08-24 14:36:48 +00004018 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4019 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4020 ", distance=%" PRIu64,
4021 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004022 break;
4023 }
4024 }
4025
4026 // Assign fresh ids to pointers that were not matched in the process.
4027 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4028 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4029 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4030
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004031 current.rawPointerData.pointers[currentPointerIndex].id = id;
4032 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4033 current.rawPointerData.markIdBit(id,
4034 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004035
Harry Cutts45483602022-08-24 14:36:48 +00004036 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4037 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4038 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004039 }
4040}
4041
4042int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4043 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4044 return AKEY_STATE_VIRTUAL;
4045 }
4046
4047 for (const VirtualKey& virtualKey : mVirtualKeys) {
4048 if (virtualKey.keyCode == keyCode) {
4049 return AKEY_STATE_UP;
4050 }
4051 }
4052
4053 return AKEY_STATE_UNKNOWN;
4054}
4055
4056int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4057 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4058 return AKEY_STATE_VIRTUAL;
4059 }
4060
4061 for (const VirtualKey& virtualKey : mVirtualKeys) {
4062 if (virtualKey.scanCode == scanCode) {
4063 return AKEY_STATE_UP;
4064 }
4065 }
4066
4067 return AKEY_STATE_UNKNOWN;
4068}
4069
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004070bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4071 const std::vector<int32_t>& keyCodes,
4072 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004073 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004074 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004075 if (virtualKey.keyCode == keyCodes[i]) {
4076 outFlags[i] = 1;
4077 }
4078 }
4079 }
4080
4081 return true;
4082}
4083
4084std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4085 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004086 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004087 return std::make_optional(mPointerController->getDisplayId());
4088 } else {
4089 return std::make_optional(mViewport.displayId);
4090 }
4091 }
4092 return std::nullopt;
4093}
4094
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004095} // namespace android