blob: 96c163dc3ce90ad8df53a81de1c0abd78dad713f [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
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000808 // Oriented X/Y range (in the rotated display's orientation)
809 const FloatRect rawFrame = Rect{mRawPointerAxes.x.minValue, mRawPointerAxes.y.minValue,
810 mRawPointerAxes.x.maxValue, mRawPointerAxes.y.maxValue}
811 .toFloatRect();
812 const auto orientedRangeRect = mRawToRotatedDisplay.transform(rawFrame);
813 mOrientedRanges.x.min = orientedRangeRect.left;
814 mOrientedRanges.y.min = orientedRangeRect.top;
815 mOrientedRanges.x.max = orientedRangeRect.right;
816 mOrientedRanges.y.max = orientedRangeRect.bottom;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800817
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000818 // Oriented flat (in the rotated display's orientation)
819 const auto orientedFlat =
820 transformWithoutTranslation(mRawToRotatedDisplay,
821 {static_cast<float>(mRawPointerAxes.x.flat),
822 static_cast<float>(mRawPointerAxes.y.flat)});
823 mOrientedRanges.x.flat = std::abs(orientedFlat.x);
824 mOrientedRanges.y.flat = std::abs(orientedFlat.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800825
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000826 // Oriented fuzz (in the rotated display's orientation)
827 const auto orientedFuzz =
828 transformWithoutTranslation(mRawToRotatedDisplay,
829 {static_cast<float>(mRawPointerAxes.x.fuzz),
830 static_cast<float>(mRawPointerAxes.y.fuzz)});
831 mOrientedRanges.x.fuzz = std::abs(orientedFuzz.x);
832 mOrientedRanges.y.fuzz = std::abs(orientedFuzz.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800833
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000834 // Oriented resolution (in the rotated display's orientation)
835 const auto orientedRes =
836 transformWithoutTranslation(mRawToRotatedDisplay,
837 {static_cast<float>(mRawPointerAxes.x.resolution),
838 static_cast<float>(mRawPointerAxes.y.resolution)});
839 mOrientedRanges.x.resolution = std::abs(orientedRes.x);
840 mOrientedRanges.y.resolution = std::abs(orientedRes.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800841}
842
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000843void TouchInputMapper::computeInputTransforms() {
Prabir Pradhan3e798762022-12-02 21:02:11 +0000844 constexpr auto isRotated = [](const ui::Transform::RotationFlags& rotation) {
845 return rotation == ui::Transform::ROT_90 || rotation == ui::Transform::ROT_270;
846 };
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000847
Prabir Pradhan3e798762022-12-02 21:02:11 +0000848 // See notes about input coordinates in the inputflinger docs:
849 // //frameworks/native/services/inputflinger/docs/input_coordinates.md
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000850
851 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
Prabir Pradhan3e798762022-12-02 21:02:11 +0000852 ui::Transform undoOffsetInRaw;
853 undoOffsetInRaw.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000854
Prabir Pradhan3e798762022-12-02 21:02:11 +0000855 // Step 2: Rotate the raw coordinates to account for input device orientation. The coordinates
856 // will now be in the same orientation as the display in ROTATION_0.
857 // Note: Negating an ui::Rotation value will give its inverse rotation.
858 const auto inputDeviceOrientation = ui::Transform::toRotationFlags(-mParameters.orientation);
859 const ui::Size orientedRawSize = isRotated(inputDeviceOrientation)
860 ? ui::Size{mRawPointerAxes.getRawHeight(), mRawPointerAxes.getRawWidth()}
861 : ui::Size{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
862 // When rotating raw values, account for the extra unit added when calculating the raw range.
863 const auto orientInRaw = ui::Transform(inputDeviceOrientation, orientedRawSize.width - 1,
864 orientedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000865
Prabir Pradhan3e798762022-12-02 21:02:11 +0000866 // Step 3: Rotate the raw coordinates to account for the display rotation. The coordinates will
867 // now be in the same orientation as the rotated display. There is no need to rotate the
868 // coordinates to the display rotation if the device is not orientation-aware.
869 const auto viewportRotation = ui::Transform::toRotationFlags(-mViewport.orientation);
870 const auto rotatedRawSize = mParameters.orientationAware && isRotated(viewportRotation)
871 ? ui::Size{orientedRawSize.height, orientedRawSize.width}
872 : orientedRawSize;
873 // When rotating raw values, account for the extra unit added when calculating the raw range.
874 const auto rotateInRaw = mParameters.orientationAware
875 ? ui::Transform(viewportRotation, rotatedRawSize.width - 1, rotatedRawSize.height - 1)
876 : ui::Transform();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000877
Prabir Pradhan3e798762022-12-02 21:02:11 +0000878 // Step 4: Scale the raw coordinates to the display space.
879 // - Here, we assume that the raw surface of the touch device maps perfectly to the surface
880 // of the display panel. This is usually true for touchscreens.
881 // - From this point onward, we are no longer in the discrete space of the raw coordinates but
882 // are in the continuous space of the logical display.
883 ui::Transform scaleRawToDisplay;
884 const float xScale = static_cast<float>(mViewport.deviceWidth) / rotatedRawSize.width;
885 const float yScale = static_cast<float>(mViewport.deviceHeight) / rotatedRawSize.height;
886 scaleRawToDisplay.set(xScale, 0, 0, yScale);
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000887
Prabir Pradhan3e798762022-12-02 21:02:11 +0000888 // Step 5: Undo the display rotation to bring us back to the un-rotated display coordinate space
889 // that InputReader uses.
890 const auto undoRotateInDisplay =
891 ui::Transform(viewportRotation, mViewport.deviceWidth, mViewport.deviceHeight)
892 .inverse();
893
894 // Now put it all together!
895 mRawToRotatedDisplay = (scaleRawToDisplay * (rotateInRaw * (orientInRaw * undoOffsetInRaw)));
896 mRawToDisplay = (undoRotateInDisplay * mRawToRotatedDisplay);
897 mRawRotation = ui::Transform{mRawToDisplay.getOrientation()};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000898}
899
Prabir Pradhan1728b212021-10-19 16:00:03 -0700900void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000901 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700902
903 resolveExternalStylusPresence();
904
905 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100906 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000907 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700908 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100909 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700910 if (hasStylus()) {
911 mSource |= AINPUT_SOURCE_STYLUS;
912 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800913 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700914 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100915 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700916 if (hasStylus()) {
917 mSource |= AINPUT_SOURCE_STYLUS;
918 }
919 if (hasExternalStylus()) {
920 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
921 }
Michael Wright227c5542020-07-02 18:30:52 +0100922 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700923 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100924 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700925 } else {
926 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100927 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700928 }
929
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000930 const std::optional<DisplayViewport> newViewportOpt = findViewport();
931
932 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700933 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
934 ALOGW("Touch device '%s' did not report support for X or Y axis! "
935 "The device will be inoperable.",
936 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100937 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000938 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700939 ALOGI("Touch device '%s' could not query the properties of its associated "
940 "display. The device will be inoperable until the display size "
941 "becomes available.",
942 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100943 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700944 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000945 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
946 getDeviceName().c_str(), getDeviceId());
947 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000948 }
949
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700950 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000951 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000952 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
953 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
954 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
955 const float rawMeanResolution =
956 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700957
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000958 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
959 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700960 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700961 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000962 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
963 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
964 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700965
Michael Wright227c5542020-07-02 18:30:52 +0100966 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000967 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700968
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000969 mDisplayBounds = getNaturalDisplaySize(mViewport);
970 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
971 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700972
Prabir Pradhan3e798762022-12-02 21:02:11 +0000973 // TODO(b/257118693): Remove the dependence on the old orientation/rotation logic that
974 // uses mInputDeviceOrientation. The new logic uses the transforms calculated in
975 // computeInputTransforms().
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000976 // InputReader works in the un-rotated display coordinate space, so we don't need to do
977 // anything if the device is already orientation-aware. If the device is not
978 // orientation-aware, then we need to apply the inverse rotation of the display so that
979 // when the display rotation is applied later as a part of the per-window transform, we
980 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700981 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +0000982 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000983 : getInverseRotation(mViewport.orientation);
984 // For orientation-aware devices that work in the un-rotated coordinate space, the
985 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000986 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000987 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700988
989 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +0000990 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000991 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700992 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000993 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000994 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +0000995 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000996 mRawToDisplay.reset();
997 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000998 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700999 }
1000 }
1001
1002 // If moving between pointer modes, need to reset some state.
1003 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1004 if (deviceModeChanged) {
1005 mOrientedRanges.clear();
1006 }
1007
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001008 // Create and preserve the pointer controller in the following cases:
1009 const bool isPointerControllerNeeded =
1010 // - when the device is in pointer mode, to show the mouse cursor;
1011 (mDeviceMode == DeviceMode::POINTER) ||
1012 // - when pointer capture is enabled, to preserve the mouse cursor position;
1013 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
1014 mConfig.pointerCaptureRequest.enable) ||
1015 // - when we should be showing touches;
1016 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
1017 // - when we should be showing a pointer icon for direct styluses.
1018 (mDeviceMode == DeviceMode::DIRECT && mConfig.stylusPointerIconEnabled && hasStylus());
1019 if (isPointerControllerNeeded) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001020 if (mPointerController == nullptr) {
1021 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001022 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001023 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001024 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1025 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001026 } else {
lilinnandef700b2022-06-17 19:32:01 +08001027 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1028 !mConfig.showTouches) {
1029 mPointerController->clearSpots();
1030 }
Michael Wright17db18e2020-06-26 20:51:44 +01001031 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001032 }
1033
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001034 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001035 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001036 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001037 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001038 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001039
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001040 configureVirtualKeys();
1041
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001042 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001043
1044 // Location
1045 updateAffineTransformation();
1046
Michael Wright227c5542020-07-02 18:30:52 +01001047 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001048 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001049 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1050 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001051
1052 // Scale movements such that one whole swipe of the touch pad covers a
1053 // given area relative to the diagonal size of the display when no acceleration
1054 // is applied.
1055 // Assume that the touch pad has a square aspect ratio such that movements in
1056 // X and Y of the same number of raw units cover the same physical distance.
1057 mPointerXMovementScale =
1058 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1059 mPointerYMovementScale = mPointerXMovementScale;
1060
1061 // Scale zooms to cover a smaller range of the display than movements do.
1062 // This value determines the area around the pointer that is affected by freeform
1063 // pointer gestures.
1064 mPointerXZoomScale =
1065 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1066 mPointerYZoomScale = mPointerXZoomScale;
1067
HQ Liue6983c72022-04-19 22:14:56 +00001068 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1069 // axis is non positive value.
1070 const float minFreeformGestureWidth =
1071 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1072
1073 mPointerGestureMaxSwipeWidth =
1074 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1075 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001076 }
1077
1078 // Inform the dispatcher about the changes.
1079 *outResetNeeded = true;
1080 bumpGeneration();
1081 }
1082}
1083
Prabir Pradhan1728b212021-10-19 16:00:03 -07001084void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001085 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001086 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001087 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1088 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001089 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001090}
1091
1092void TouchInputMapper::configureVirtualKeys() {
1093 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001094 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001095
1096 mVirtualKeys.clear();
1097
1098 if (virtualKeyDefinitions.size() == 0) {
1099 return;
1100 }
1101
1102 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1103 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1104 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1105 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1106
1107 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1108 VirtualKey virtualKey;
1109
1110 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1111 int32_t keyCode;
1112 int32_t dummyKeyMetaState;
1113 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001114 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1115 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001116 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1117 continue; // drop the key
1118 }
1119
1120 virtualKey.keyCode = keyCode;
1121 virtualKey.flags = flags;
1122
1123 // convert the key definition's display coordinates into touch coordinates for a hit box
1124 int32_t halfWidth = virtualKeyDefinition.width / 2;
1125 int32_t halfHeight = virtualKeyDefinition.height / 2;
1126
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001127 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1128 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001129 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001130 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1131 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001132 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001133 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1134 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001135 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001136 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1137 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001138 touchScreenTop;
1139 mVirtualKeys.push_back(virtualKey);
1140 }
1141}
1142
1143void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1144 if (!mVirtualKeys.empty()) {
1145 dump += INDENT3 "Virtual Keys:\n";
1146
1147 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1148 const VirtualKey& virtualKey = mVirtualKeys[i];
1149 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1150 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1151 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1152 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1153 }
1154 }
1155}
1156
1157void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001158 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001159 Calibration& out = mCalibration;
1160
1161 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001162 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001163 std::string sizeCalibrationString;
1164 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001165 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001166 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001167 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001168 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001169 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001170 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001171 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001172 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001173 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001174 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001175 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001176 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001177 }
1178 }
1179
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001180 float sizeScale;
1181
1182 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1183 out.sizeScale = sizeScale;
1184 }
1185 float sizeBias;
1186 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1187 out.sizeBias = sizeBias;
1188 }
1189 bool sizeIsSummed;
1190 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1191 out.sizeIsSummed = sizeIsSummed;
1192 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193
1194 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001195 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001196 std::string pressureCalibrationString;
1197 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001198 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001199 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001200 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001201 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001202 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001203 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001204 } else if (pressureCalibrationString != "default") {
1205 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001206 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001207 }
1208 }
1209
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001210 float pressureScale;
1211 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1212 out.pressureScale = pressureScale;
1213 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214
1215 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001216 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001217 std::string orientationCalibrationString;
1218 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001219 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001220 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001221 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001222 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001223 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001224 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001225 } else if (orientationCalibrationString != "default") {
1226 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001227 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001228 }
1229 }
1230
1231 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001232 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001233 std::string distanceCalibrationString;
1234 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001235 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001236 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001237 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001238 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001239 } else if (distanceCalibrationString != "default") {
1240 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001241 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001242 }
1243 }
1244
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001245 float distanceScale;
1246 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1247 out.distanceScale = distanceScale;
1248 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001249}
1250
1251void TouchInputMapper::resolveCalibration() {
1252 // Size
1253 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001254 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1255 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001256 }
1257 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001258 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001259 }
1260
1261 // Pressure
1262 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001263 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1264 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001265 }
1266 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001267 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001268 }
1269
1270 // Orientation
1271 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001272 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1273 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001274 }
1275 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001276 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001277 }
1278
1279 // Distance
1280 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001281 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1282 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001283 }
1284 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001285 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001286 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287}
1288
1289void TouchInputMapper::dumpCalibration(std::string& dump) {
1290 dump += INDENT3 "Calibration:\n";
1291
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001292 dump += INDENT4 "touch.size.calibration: ";
1293 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001294
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001295 if (mCalibration.sizeScale) {
1296 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001297 }
1298
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001299 if (mCalibration.sizeBias) {
1300 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 }
1302
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001303 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001304 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001305 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001306 }
1307
1308 // Pressure
1309 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001310 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001311 dump += INDENT4 "touch.pressure.calibration: none\n";
1312 break;
Michael Wright227c5542020-07-02 18:30:52 +01001313 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001314 dump += INDENT4 "touch.pressure.calibration: physical\n";
1315 break;
Michael Wright227c5542020-07-02 18:30:52 +01001316 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001317 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1318 break;
1319 default:
1320 ALOG_ASSERT(false);
1321 }
1322
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001323 if (mCalibration.pressureScale) {
1324 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001325 }
1326
1327 // Orientation
1328 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001329 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001330 dump += INDENT4 "touch.orientation.calibration: none\n";
1331 break;
Michael Wright227c5542020-07-02 18:30:52 +01001332 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001333 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1334 break;
Michael Wright227c5542020-07-02 18:30:52 +01001335 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001336 dump += INDENT4 "touch.orientation.calibration: vector\n";
1337 break;
1338 default:
1339 ALOG_ASSERT(false);
1340 }
1341
1342 // Distance
1343 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001344 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001345 dump += INDENT4 "touch.distance.calibration: none\n";
1346 break;
Michael Wright227c5542020-07-02 18:30:52 +01001347 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001348 dump += INDENT4 "touch.distance.calibration: scaled\n";
1349 break;
1350 default:
1351 ALOG_ASSERT(false);
1352 }
1353
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001354 if (mCalibration.distanceScale) {
1355 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001356 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001357}
1358
1359void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1360 dump += INDENT3 "Affine Transformation:\n";
1361
1362 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1363 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1364 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1365 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1366 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1367 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1368}
1369
1370void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001371 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001372 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001373}
1374
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001375std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001376 std::list<NotifyArgs> out = cancelTouch(when, when);
1377 updateTouchSpots();
1378
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001379 mCursorButtonAccumulator.reset(getDeviceContext());
1380 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001381 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001382
1383 mPointerVelocityControl.reset();
1384 mWheelXVelocityControl.reset();
1385 mWheelYVelocityControl.reset();
1386
1387 mRawStatesPending.clear();
1388 mCurrentRawState.clear();
1389 mCurrentCookedState.clear();
1390 mLastRawState.clear();
1391 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001392 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001393 mSentHoverEnter = false;
1394 mHavePointerIds = false;
1395 mCurrentMotionAborted = false;
1396 mDownTime = 0;
1397
1398 mCurrentVirtualKey.down = false;
1399
1400 mPointerGesture.reset();
1401 mPointerSimple.reset();
1402 resetExternalStylus();
1403
1404 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001405 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001406 mPointerController->clearSpots();
1407 }
1408
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001409 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001410}
1411
1412void TouchInputMapper::resetExternalStylus() {
1413 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001414 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001415 mExternalStylusFusionTimeout = LLONG_MAX;
1416 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001417 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001418}
1419
1420void TouchInputMapper::clearStylusDataPendingFlags() {
1421 mExternalStylusDataPending = false;
1422 mExternalStylusFusionTimeout = LLONG_MAX;
1423}
1424
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001425std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001426 mCursorButtonAccumulator.process(rawEvent);
1427 mCursorScrollAccumulator.process(rawEvent);
1428 mTouchButtonAccumulator.process(rawEvent);
1429
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001430 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001431 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001432 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001433 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001434 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001435}
1436
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001437std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1438 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001439 if (mDeviceMode == DeviceMode::DISABLED) {
1440 // Only save the last pending state when the device is disabled.
1441 mRawStatesPending.clear();
1442 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001443 // Push a new state.
1444 mRawStatesPending.emplace_back();
1445
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001446 RawState& next = mRawStatesPending.back();
1447 next.clear();
1448 next.when = when;
1449 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001450
1451 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001452 next.buttonState = filterButtonState(mConfig,
1453 mTouchButtonAccumulator.getButtonState() |
1454 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001455
1456 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001457 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1458 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001459 mCursorScrollAccumulator.finishSync();
1460
1461 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001462 syncTouch(when, &next);
1463
1464 // The last RawState is the actually second to last, since we just added a new state
1465 const RawState& last =
1466 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001467
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001468 std::tie(next.when, next.readTime) =
1469 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1470 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001471
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001472 // Assign pointer ids.
1473 if (!mHavePointerIds) {
1474 assignPointerIds(last, next);
1475 }
1476
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001477 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001478 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1479 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1480 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1481 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1482 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1483 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001484
Arthur Hung9ad18942021-06-19 02:04:46 +00001485 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1486 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1487 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1488 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1489 next.rawPointerData.hoveringIdBits.value);
1490 }
1491
Harry Cutts33476232023-01-30 19:57:29 +00001492 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001493 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001494}
1495
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001496std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1497 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001498 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001499 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001500 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001501 }
1502
1503 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1504 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1505 // touching the current state will only observe the events that have been dispatched to the
1506 // rest of the pipeline.
1507 const size_t N = mRawStatesPending.size();
1508 size_t count;
1509 for (count = 0; count < N; count++) {
1510 const RawState& next = mRawStatesPending[count];
1511
1512 // A failure to assign the stylus id means that we're waiting on stylus data
1513 // and so should defer the rest of the pipeline.
1514 if (assignExternalStylusId(next, timeout)) {
1515 break;
1516 }
1517
1518 // All ready to go.
1519 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001520 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001521 if (mCurrentRawState.when < mLastRawState.when) {
1522 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001523 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001524 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001525 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001526 }
1527 if (count != 0) {
1528 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1529 }
1530
1531 if (mExternalStylusDataPending) {
1532 if (timeout) {
1533 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1534 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001535 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001536 ALOGD_IF(DEBUG_STYLUS_FUSION,
1537 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001538 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001539 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001540 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1541 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1542 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1543 }
1544 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001545 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001546}
1547
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001548std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1549 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001550 // Always start with a clean state.
1551 mCurrentCookedState.clear();
1552
1553 // Apply stylus buttons to current raw state.
1554 applyExternalStylusButtonState(when);
1555
1556 // Handle policy on initial down or hover events.
1557 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1558 mCurrentRawState.rawPointerData.pointerCount != 0;
1559
1560 uint32_t policyFlags = 0;
1561 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1562 if (initialDown || buttonsPressed) {
1563 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001564 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001565 getContext()->fadePointer();
1566 }
1567
1568 if (mParameters.wake) {
1569 policyFlags |= POLICY_FLAG_WAKE;
1570 }
1571 }
1572
1573 // Consume raw off-screen touches before cooking pointer data.
1574 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001575 bool consumed;
1576 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1577 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001578 mCurrentRawState.rawPointerData.clear();
1579 }
1580
1581 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1582 // with cooked pointer data that has the same ids and indices as the raw data.
1583 // The following code can use either the raw or cooked data, as needed.
1584 cookPointerData();
1585
1586 // Apply stylus pressure to current cooked state.
1587 applyExternalStylusTouchState(when);
1588
1589 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001590 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1591 mSource, mViewport.displayId, policyFlags,
1592 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001593
1594 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001595 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001596 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1597 uint32_t id = idBits.clearFirstMarkedBit();
1598 const RawPointerData::Pointer& pointer =
1599 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001600 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001601 mCurrentCookedState.stylusIdBits.markBit(id);
1602 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1603 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1604 mCurrentCookedState.fingerIdBits.markBit(id);
1605 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1606 mCurrentCookedState.mouseIdBits.markBit(id);
1607 }
1608 }
1609 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1610 uint32_t id = idBits.clearFirstMarkedBit();
1611 const RawPointerData::Pointer& pointer =
1612 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001613 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001614 mCurrentCookedState.stylusIdBits.markBit(id);
1615 }
1616 }
1617
1618 // Stylus takes precedence over all tools, then mouse, then finger.
1619 PointerUsage pointerUsage = mPointerUsage;
1620 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1621 mCurrentCookedState.mouseIdBits.clear();
1622 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001623 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001624 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1625 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001626 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001627 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1628 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001629 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001630 }
1631
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001632 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001633 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001634 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001635 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001636 out += dispatchButtonRelease(when, readTime, policyFlags);
1637 out += dispatchHoverExit(when, readTime, policyFlags);
1638 out += dispatchTouches(when, readTime, policyFlags);
1639 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1640 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001641 }
1642
1643 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1644 mCurrentMotionAborted = false;
1645 }
1646 }
1647
1648 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001649 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1650 mSource, mViewport.displayId, policyFlags,
1651 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001652
1653 // Clear some transient state.
1654 mCurrentRawState.rawVScroll = 0;
1655 mCurrentRawState.rawHScroll = 0;
1656
1657 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001658 mLastRawState = mCurrentRawState;
1659 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001660 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001661}
1662
Garfield Tanc734e4f2021-01-15 20:01:39 -08001663void TouchInputMapper::updateTouchSpots() {
1664 if (!mConfig.showTouches || mPointerController == nullptr) {
1665 return;
1666 }
1667
1668 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1669 // clear touch spots.
1670 if (mDeviceMode != DeviceMode::DIRECT &&
1671 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1672 return;
1673 }
1674
1675 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1676 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1677
1678 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001679 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1680 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhanb3ce4532023-03-03 22:20:54 +00001681 mCurrentCookedState.cookedPointerData.touchingIdBits |
1682 mCurrentCookedState.cookedPointerData.hoveringIdBits,
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001683 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001684}
1685
1686bool TouchInputMapper::isTouchScreen() {
1687 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1688 mParameters.hasAssociatedDisplay;
1689}
1690
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001691void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001692 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1693 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001694 const int32_t pressedButtons =
1695 filterButtonState(mConfig,
1696 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001697 const int32_t releasedButtons =
1698 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1699
1700 mCurrentRawState.buttonState |= pressedButtons;
1701 mCurrentRawState.buttonState &= ~releasedButtons;
1702
1703 mExternalStylusButtonsApplied |= pressedButtons;
1704 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001705 }
1706}
1707
1708void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1709 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1710 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001711 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1712 return;
1713 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001714
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001715 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1716 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1717 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1718 : 0.f;
1719 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1720 pressure = *mExternalStylusState.pressure;
1721 }
1722 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1723 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001724
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001725 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001726 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001727 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001728 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001729 }
1730}
1731
1732bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001733 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001734 return false;
1735 }
1736
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001737 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001738 if (mFusedStylusPointerId &&
1739 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001740 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001741 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001742 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001743 }
1744
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001745 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1746 state.rawPointerData.pointerCount != 0;
1747 if (!initialDown) {
1748 return false;
1749 }
1750
1751 if (!mExternalStylusState.pressure) {
1752 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1753 return false;
1754 }
1755
1756 if (*mExternalStylusState.pressure != 0.0f) {
1757 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1758 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1759 return false;
1760 }
1761
1762 if (timeout) {
1763 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1764 mFusedStylusPointerId.reset();
1765 mExternalStylusFusionTimeout = LLONG_MAX;
1766 return false;
1767 }
1768
1769 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1770 // being processed until we either get pressure data or timeout.
1771 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1772 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1773 }
1774 ALOGD_IF(DEBUG_STYLUS_FUSION,
1775 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1776 mExternalStylusFusionTimeout);
1777 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1778 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001779}
1780
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001781std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1782 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001783 if (mDeviceMode == DeviceMode::POINTER) {
1784 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001785 // Since this is a synthetic event, we can consider its latency to be zero
1786 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001787 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001788 }
Michael Wright227c5542020-07-02 18:30:52 +01001789 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001790 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001791 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001792 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1793 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1794 }
1795 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001796 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001797}
1798
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001799std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1800 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001801 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001802 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001803 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001804 // The following three cases are handled here:
1805 // - We're in the middle of a fused stream of data;
1806 // - We're waiting on external stylus data before dispatching the initial down; or
1807 // - Only the button state, which is not reported through a specific pointer, has changed.
1808 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001809 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001810 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001811 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001812 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001813}
1814
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001815std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1816 uint32_t policyFlags, bool& outConsumed) {
1817 outConsumed = false;
1818 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001819 // Check for release of a virtual key.
1820 if (mCurrentVirtualKey.down) {
1821 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1822 // Pointer went up while virtual key was down.
1823 mCurrentVirtualKey.down = false;
1824 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001825 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1826 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1827 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001828 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1829 AKEY_EVENT_FLAG_FROM_SYSTEM |
1830 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001831 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001832 outConsumed = true;
1833 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001834 }
1835
1836 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1837 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1838 const RawPointerData::Pointer& pointer =
1839 mCurrentRawState.rawPointerData.pointerForId(id);
1840 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1841 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1842 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001843 outConsumed = true;
1844 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001845 }
1846 }
1847
1848 // Pointer left virtual key area or another pointer also went down.
1849 // Send key cancellation but do not consume the touch yet.
1850 // This is useful when the user swipes through from the virtual key area
1851 // into the main display surface.
1852 mCurrentVirtualKey.down = false;
1853 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001854 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1855 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001856 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1857 AKEY_EVENT_FLAG_FROM_SYSTEM |
1858 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1859 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001860 }
1861 }
1862
1863 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1864 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1865 // Pointer just went down. Check for virtual key press or off-screen touches.
1866 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1867 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001868 // Skip checking whether the pointer is inside the physical frame if the device is in
1869 // unscaled mode.
1870 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1871 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001872 // If exactly one pointer went down, check for virtual key hit.
1873 // Otherwise we will drop the entire stroke.
1874 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1875 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1876 if (virtualKey) {
1877 mCurrentVirtualKey.down = true;
1878 mCurrentVirtualKey.downTime = when;
1879 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1880 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1881 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001882 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1883 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001884
1885 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001886 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1887 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1888 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001889 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1890 AKEY_EVENT_ACTION_DOWN,
1891 AKEY_EVENT_FLAG_FROM_SYSTEM |
1892 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001893 }
1894 }
1895 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001896 outConsumed = true;
1897 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001898 }
1899 }
1900
1901 // Disable all virtual key touches that happen within a short time interval of the
1902 // most recent touch within the screen area. The idea is to filter out stray
1903 // virtual key presses when interacting with the touch screen.
1904 //
1905 // Problems we're trying to solve:
1906 //
1907 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1908 // virtual key area that is implemented by a separate touch panel and accidentally
1909 // triggers a virtual key.
1910 //
1911 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1912 // area and accidentally triggers a virtual key. This often happens when virtual keys
1913 // are layed out below the screen near to where the on screen keyboard's space bar
1914 // is displayed.
1915 if (mConfig.virtualKeyQuietTime > 0 &&
1916 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001917 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001918 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001919 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001920}
1921
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001922NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1923 uint32_t policyFlags, int32_t keyEventAction,
1924 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001925 int32_t keyCode = mCurrentVirtualKey.keyCode;
1926 int32_t scanCode = mCurrentVirtualKey.scanCode;
1927 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001928 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001929 policyFlags |= POLICY_FLAG_VIRTUAL;
1930
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001931 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1932 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1933 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001934}
1935
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001936std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1937 uint32_t policyFlags) {
1938 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001939 if (mCurrentMotionAborted) {
1940 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001941 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001942 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001943 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1944 if (!currentIdBits.isEmpty()) {
1945 int32_t metaState = getContext()->getGlobalMetaState();
1946 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001947 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001948 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1949 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001950 mCurrentCookedState.cookedPointerData.pointerProperties,
1951 mCurrentCookedState.cookedPointerData.pointerCoords,
1952 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1953 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1954 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001955 mCurrentMotionAborted = true;
1956 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001957 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001958}
1959
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001960// Updates pointer coords and properties for pointers with specified ids that have moved.
1961// Returns true if any of them changed.
1962static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1963 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1964 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1965 BitSet32 idBits) {
1966 bool changed = false;
1967 while (!idBits.isEmpty()) {
1968 uint32_t id = idBits.clearFirstMarkedBit();
1969 uint32_t inIndex = inIdToIndex[id];
1970 uint32_t outIndex = outIdToIndex[id];
1971
1972 const PointerProperties& curInProperties = inProperties[inIndex];
1973 const PointerCoords& curInCoords = inCoords[inIndex];
1974 PointerProperties& curOutProperties = outProperties[outIndex];
1975 PointerCoords& curOutCoords = outCoords[outIndex];
1976
1977 if (curInProperties != curOutProperties) {
1978 curOutProperties.copyFrom(curInProperties);
1979 changed = true;
1980 }
1981
1982 if (curInCoords != curOutCoords) {
1983 curOutCoords.copyFrom(curInCoords);
1984 changed = true;
1985 }
1986 }
1987 return changed;
1988}
1989
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001990std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1991 uint32_t policyFlags) {
1992 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001993 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1994 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1995 int32_t metaState = getContext()->getGlobalMetaState();
1996 int32_t buttonState = mCurrentCookedState.buttonState;
1997
1998 if (currentIdBits == lastIdBits) {
1999 if (!currentIdBits.isEmpty()) {
2000 // No pointer id changes so this is a move event.
2001 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002002 out.push_back(
2003 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2004 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2005 mCurrentCookedState.cookedPointerData.pointerProperties,
2006 mCurrentCookedState.cookedPointerData.pointerCoords,
2007 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2008 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2009 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002010 }
2011 } else {
2012 // There may be pointers going up and pointers going down and pointers moving
2013 // all at the same time.
2014 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2015 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2016 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2017 BitSet32 dispatchedIdBits(lastIdBits.value);
2018
2019 // Update last coordinates of pointers that have moved so that we observe the new
2020 // pointer positions at the same time as other pointers that have just gone up.
2021 bool moveNeeded =
2022 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2023 mCurrentCookedState.cookedPointerData.pointerCoords,
2024 mCurrentCookedState.cookedPointerData.idToIndex,
2025 mLastCookedState.cookedPointerData.pointerProperties,
2026 mLastCookedState.cookedPointerData.pointerCoords,
2027 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2028 if (buttonState != mLastCookedState.buttonState) {
2029 moveNeeded = true;
2030 }
2031
2032 // Dispatch pointer up events.
2033 while (!upIdBits.isEmpty()) {
2034 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002035 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002036 if (isCanceled) {
2037 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2038 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002039 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2040 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2041 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2042 buttonState, 0,
2043 mLastCookedState.cookedPointerData.pointerProperties,
2044 mLastCookedState.cookedPointerData.pointerCoords,
2045 mLastCookedState.cookedPointerData.idToIndex,
2046 dispatchedIdBits, upId, mOrientedXPrecision,
2047 mOrientedYPrecision, mDownTime,
2048 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002049 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002050 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002051 }
2052
2053 // Dispatch move events if any of the remaining pointers moved from their old locations.
2054 // Although applications receive new locations as part of individual pointer up
2055 // events, they do not generally handle them except when presented in a move event.
2056 if (moveNeeded && !moveIdBits.isEmpty()) {
2057 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002058 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2059 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2060 mCurrentCookedState.cookedPointerData.pointerProperties,
2061 mCurrentCookedState.cookedPointerData.pointerCoords,
2062 mCurrentCookedState.cookedPointerData.idToIndex,
2063 dispatchedIdBits, -1, mOrientedXPrecision,
2064 mOrientedYPrecision, mDownTime,
2065 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002066 }
2067
2068 // Dispatch pointer down events using the new pointer locations.
2069 while (!downIdBits.isEmpty()) {
2070 uint32_t downId = downIdBits.clearFirstMarkedBit();
2071 dispatchedIdBits.markBit(downId);
2072
2073 if (dispatchedIdBits.count() == 1) {
2074 // First pointer is going down. Set down time.
2075 mDownTime = when;
2076 }
2077
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002078 out.push_back(
2079 dispatchMotion(when, readTime, policyFlags, mSource,
2080 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2081 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2082 mCurrentCookedState.cookedPointerData.pointerCoords,
2083 mCurrentCookedState.cookedPointerData.idToIndex,
2084 dispatchedIdBits, downId, mOrientedXPrecision,
2085 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002086 }
2087 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002088 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002089}
2090
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002091std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2092 uint32_t policyFlags) {
2093 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002094 if (mSentHoverEnter &&
2095 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2096 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2097 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002098 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2099 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2100 mLastCookedState.buttonState, 0,
2101 mLastCookedState.cookedPointerData.pointerProperties,
2102 mLastCookedState.cookedPointerData.pointerCoords,
2103 mLastCookedState.cookedPointerData.idToIndex,
2104 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2105 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2106 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002107 mSentHoverEnter = false;
2108 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002109 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002110}
2111
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002112std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2113 uint32_t policyFlags) {
2114 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002115 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2116 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2117 int32_t metaState = getContext()->getGlobalMetaState();
2118 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002119 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2120 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2121 mCurrentRawState.buttonState, 0,
2122 mCurrentCookedState.cookedPointerData.pointerProperties,
2123 mCurrentCookedState.cookedPointerData.pointerCoords,
2124 mCurrentCookedState.cookedPointerData.idToIndex,
2125 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2126 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2127 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002128 mSentHoverEnter = true;
2129 }
2130
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002131 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2132 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2133 mCurrentRawState.buttonState, 0,
2134 mCurrentCookedState.cookedPointerData.pointerProperties,
2135 mCurrentCookedState.cookedPointerData.pointerCoords,
2136 mCurrentCookedState.cookedPointerData.idToIndex,
2137 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2138 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2139 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002140 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002141 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002142}
2143
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002144std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2145 uint32_t policyFlags) {
2146 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002147 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2148 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2149 const int32_t metaState = getContext()->getGlobalMetaState();
2150 int32_t buttonState = mLastCookedState.buttonState;
2151 while (!releasedButtons.isEmpty()) {
2152 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2153 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002154 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2155 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2156 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002157 mLastCookedState.cookedPointerData.pointerProperties,
2158 mLastCookedState.cookedPointerData.pointerCoords,
2159 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002160 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2161 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002162 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002163 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002164}
2165
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002166std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2167 uint32_t policyFlags) {
2168 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002169 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2170 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2171 const int32_t metaState = getContext()->getGlobalMetaState();
2172 int32_t buttonState = mLastCookedState.buttonState;
2173 while (!pressedButtons.isEmpty()) {
2174 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2175 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002176 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2177 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2178 buttonState, 0,
2179 mCurrentCookedState.cookedPointerData.pointerProperties,
2180 mCurrentCookedState.cookedPointerData.pointerCoords,
2181 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2182 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2183 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002184 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002185 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002186}
2187
LiZhihong758eb562022-11-03 15:28:29 +08002188std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2189 uint32_t policyFlags,
2190 BitSet32 idBits,
2191 nsecs_t readTime) {
2192 std::list<NotifyArgs> out;
2193 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2194 const int32_t metaState = getContext()->getGlobalMetaState();
2195 int32_t buttonState = mLastCookedState.buttonState;
2196
2197 while (!releasedButtons.isEmpty()) {
2198 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2199 buttonState &= ~actionButton;
2200 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2201 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2202 metaState, buttonState, 0,
2203 mPointerGesture.lastGestureProperties,
2204 mPointerGesture.lastGestureCoords,
2205 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2206 mOrientedXPrecision, mOrientedYPrecision,
2207 mPointerGesture.downTime, MotionClassification::NONE));
2208 }
2209 return out;
2210}
2211
2212std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2213 uint32_t policyFlags,
2214 BitSet32 idBits,
2215 nsecs_t readTime) {
2216 std::list<NotifyArgs> out;
2217 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2218 const int32_t metaState = getContext()->getGlobalMetaState();
2219 int32_t buttonState = mLastCookedState.buttonState;
2220
2221 while (!pressedButtons.isEmpty()) {
2222 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2223 buttonState |= actionButton;
2224 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2225 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2226 buttonState, 0, mPointerGesture.currentGestureProperties,
2227 mPointerGesture.currentGestureCoords,
2228 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2229 mOrientedXPrecision, mOrientedYPrecision,
2230 mPointerGesture.downTime, MotionClassification::NONE));
2231 }
2232 return out;
2233}
2234
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002235const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2236 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2237 return cookedPointerData.touchingIdBits;
2238 }
2239 return cookedPointerData.hoveringIdBits;
2240}
2241
2242void TouchInputMapper::cookPointerData() {
2243 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2244
2245 mCurrentCookedState.cookedPointerData.clear();
2246 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2247 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2248 mCurrentRawState.rawPointerData.hoveringIdBits;
2249 mCurrentCookedState.cookedPointerData.touchingIdBits =
2250 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002251 mCurrentCookedState.cookedPointerData.canceledIdBits =
2252 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002253
2254 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2255 mCurrentCookedState.buttonState = 0;
2256 } else {
2257 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2258 }
2259
2260 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002261 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002262 for (uint32_t i = 0; i < currentPointerCount; i++) {
2263 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2264
2265 // Size
2266 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2267 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002268 case Calibration::SizeCalibration::GEOMETRIC:
2269 case Calibration::SizeCalibration::DIAMETER:
2270 case Calibration::SizeCalibration::BOX:
2271 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002272 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2273 touchMajor = in.touchMajor;
2274 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2275 toolMajor = in.toolMajor;
2276 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2277 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2278 : in.touchMajor;
2279 } else if (mRawPointerAxes.touchMajor.valid) {
2280 toolMajor = touchMajor = in.touchMajor;
2281 toolMinor = touchMinor =
2282 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2283 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2284 : in.touchMajor;
2285 } else if (mRawPointerAxes.toolMajor.valid) {
2286 touchMajor = toolMajor = in.toolMajor;
2287 touchMinor = toolMinor =
2288 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2289 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2290 : in.toolMajor;
2291 } else {
2292 ALOG_ASSERT(false,
2293 "No touch or tool axes. "
2294 "Size calibration should have been resolved to NONE.");
2295 touchMajor = 0;
2296 touchMinor = 0;
2297 toolMajor = 0;
2298 toolMinor = 0;
2299 size = 0;
2300 }
2301
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002302 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002303 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2304 if (touchingCount > 1) {
2305 touchMajor /= touchingCount;
2306 touchMinor /= touchingCount;
2307 toolMajor /= touchingCount;
2308 toolMinor /= touchingCount;
2309 size /= touchingCount;
2310 }
2311 }
2312
Michael Wright227c5542020-07-02 18:30:52 +01002313 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002314 touchMajor *= mGeometricScale;
2315 touchMinor *= mGeometricScale;
2316 toolMajor *= mGeometricScale;
2317 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002318 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002319 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2320 touchMinor = touchMajor;
2321 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2322 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002323 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002324 touchMinor = touchMajor;
2325 toolMinor = toolMajor;
2326 }
2327
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002328 mCalibration.applySizeScaleAndBias(touchMajor);
2329 mCalibration.applySizeScaleAndBias(touchMinor);
2330 mCalibration.applySizeScaleAndBias(toolMajor);
2331 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002332 size *= mSizeScale;
2333 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002334 case Calibration::SizeCalibration::DEFAULT:
2335 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2336 break;
2337 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002338 touchMajor = 0;
2339 touchMinor = 0;
2340 toolMajor = 0;
2341 toolMinor = 0;
2342 size = 0;
2343 break;
2344 }
2345
2346 // Pressure
2347 float pressure;
2348 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002349 case Calibration::PressureCalibration::PHYSICAL:
2350 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002351 pressure = in.pressure * mPressureScale;
2352 break;
2353 default:
2354 pressure = in.isHovering ? 0 : 1;
2355 break;
2356 }
2357
2358 // Tilt and Orientation
2359 float tilt;
2360 float orientation;
2361 if (mHaveTilt) {
2362 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2363 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002364 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002365 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2366 } else {
2367 tilt = 0;
2368
2369 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002370 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002371 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002372 break;
Michael Wright227c5542020-07-02 18:30:52 +01002373 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002374 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2375 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2376 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002377 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002378 float confidence = hypotf(c1, c2);
2379 float scale = 1.0f + confidence / 16.0f;
2380 touchMajor *= scale;
2381 touchMinor /= scale;
2382 toolMajor *= scale;
2383 toolMinor /= scale;
2384 } else {
2385 orientation = 0;
2386 }
2387 break;
2388 }
2389 default:
2390 orientation = 0;
2391 }
2392 }
2393
2394 // Distance
2395 float distance;
2396 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002397 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002398 distance = in.distance * mDistanceScale;
2399 break;
2400 default:
2401 distance = 0;
2402 }
2403
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002404 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2405 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002406 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2407 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002408
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002409 // Write output coords.
2410 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2411 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002412 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2413 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002414 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2415 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2416 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2417 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2418 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2419 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2420 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002421 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2422 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002423
Chris Ye364fdb52020-08-05 15:07:56 -07002424 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002425 uint32_t id = in.id;
2426 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2427 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2428 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002429 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2430 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002431 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2432 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2433 }
2434
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002435 // Write output properties.
2436 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002437 properties.clear();
2438 properties.id = id;
2439 properties.toolType = in.toolType;
2440
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002441 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002442 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002443 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002444 }
2445}
2446
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002447std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2448 uint32_t policyFlags,
2449 PointerUsage pointerUsage) {
2450 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002451 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002452 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002453 mPointerUsage = pointerUsage;
2454 }
2455
2456 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002457 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002458 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002459 break;
Michael Wright227c5542020-07-02 18:30:52 +01002460 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002461 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002462 break;
Michael Wright227c5542020-07-02 18:30:52 +01002463 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002464 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002465 break;
Michael Wright227c5542020-07-02 18:30:52 +01002466 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002467 break;
2468 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002469 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002470}
2471
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002472std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2473 uint32_t policyFlags) {
2474 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002475 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002476 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002477 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002478 break;
Michael Wright227c5542020-07-02 18:30:52 +01002479 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002480 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002481 break;
Michael Wright227c5542020-07-02 18:30:52 +01002482 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002483 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002484 break;
Michael Wright227c5542020-07-02 18:30:52 +01002485 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002486 break;
2487 }
2488
Michael Wright227c5542020-07-02 18:30:52 +01002489 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002490 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002491}
2492
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002493std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2494 uint32_t policyFlags,
2495 bool isTimeout) {
2496 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002497 // Update current gesture coordinates.
2498 bool cancelPreviousGesture, finishPreviousGesture;
2499 bool sendEvents =
2500 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2501 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002502 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002503 }
2504 if (finishPreviousGesture) {
2505 cancelPreviousGesture = false;
2506 }
2507
2508 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002509 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002510 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002511 if (finishPreviousGesture || cancelPreviousGesture) {
2512 mPointerController->clearSpots();
2513 }
2514
Michael Wright227c5542020-07-02 18:30:52 +01002515 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002516 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2517 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002518 mPointerGesture.currentGestureIdBits,
2519 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002520 }
2521 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002522 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002523 }
2524
2525 // Show or hide the pointer if needed.
2526 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002527 case PointerGesture::Mode::NEUTRAL:
2528 case PointerGesture::Mode::QUIET:
2529 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2530 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002531 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002532 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002533 }
2534 break;
Michael Wright227c5542020-07-02 18:30:52 +01002535 case PointerGesture::Mode::TAP:
2536 case PointerGesture::Mode::TAP_DRAG:
2537 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2538 case PointerGesture::Mode::HOVER:
2539 case PointerGesture::Mode::PRESS:
2540 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002541 // Unfade the pointer when the current gesture manipulates the
2542 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002543 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002544 break;
Michael Wright227c5542020-07-02 18:30:52 +01002545 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002546 // Fade the pointer when the current gesture manipulates a different
2547 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002548 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002549 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002550 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002551 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002552 }
2553 break;
2554 }
2555
2556 // Send events!
2557 int32_t metaState = getContext()->getGlobalMetaState();
2558 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002559 const MotionClassification classification =
2560 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2561 ? MotionClassification::TWO_FINGER_SWIPE
2562 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002563
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002564 uint32_t flags = 0;
2565
2566 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2567 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2568 }
2569
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002570 // Update last coordinates of pointers that have moved so that we observe the new
2571 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002572 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2573 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2574 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2575 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2576 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2577 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002578 bool moveNeeded = false;
2579 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2580 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2581 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2582 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2583 mPointerGesture.lastGestureIdBits.value);
2584 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2585 mPointerGesture.currentGestureCoords,
2586 mPointerGesture.currentGestureIdToIndex,
2587 mPointerGesture.lastGestureProperties,
2588 mPointerGesture.lastGestureCoords,
2589 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2590 if (buttonState != mLastCookedState.buttonState) {
2591 moveNeeded = true;
2592 }
2593 }
2594
2595 // Send motion events for all pointers that went up or were canceled.
2596 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2597 if (!dispatchedGestureIdBits.isEmpty()) {
2598 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002599 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002600 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002601 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002602 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2603 mPointerGesture.lastGestureProperties,
2604 mPointerGesture.lastGestureCoords,
2605 mPointerGesture.lastGestureIdToIndex,
2606 dispatchedGestureIdBits, -1, 0, 0,
2607 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002608
2609 dispatchedGestureIdBits.clear();
2610 } else {
2611 BitSet32 upGestureIdBits;
2612 if (finishPreviousGesture) {
2613 upGestureIdBits = dispatchedGestureIdBits;
2614 } else {
2615 upGestureIdBits.value =
2616 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2617 }
2618 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002619 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2620 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2621 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2622 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2623 readTime);
2624 }
2625 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002626 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2627 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2628 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2629 mPointerGesture.lastGestureProperties,
2630 mPointerGesture.lastGestureCoords,
2631 mPointerGesture.lastGestureIdToIndex,
2632 dispatchedGestureIdBits, id, 0, 0,
2633 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002634
2635 dispatchedGestureIdBits.clearBit(id);
2636 }
2637 }
2638 }
2639
2640 // Send motion events for all pointers that moved.
2641 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002642 out.push_back(
2643 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2644 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2645 mPointerGesture.currentGestureProperties,
2646 mPointerGesture.currentGestureCoords,
2647 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2648 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002649 }
2650
2651 // Send motion events for all pointers that went down.
2652 if (down) {
2653 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2654 ~dispatchedGestureIdBits.value);
2655 while (!downGestureIdBits.isEmpty()) {
2656 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2657 dispatchedGestureIdBits.markBit(id);
2658
2659 if (dispatchedGestureIdBits.count() == 1) {
2660 mPointerGesture.downTime = when;
2661 }
2662
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002663 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2664 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2665 buttonState, 0, mPointerGesture.currentGestureProperties,
2666 mPointerGesture.currentGestureCoords,
2667 mPointerGesture.currentGestureIdToIndex,
2668 dispatchedGestureIdBits, id, 0, 0,
2669 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002670 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2671 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2672 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2673 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2674 readTime);
2675 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002676 }
2677 }
2678
2679 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002680 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002681 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2682 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2683 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2684 mPointerGesture.currentGestureProperties,
2685 mPointerGesture.currentGestureCoords,
2686 mPointerGesture.currentGestureIdToIndex,
2687 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2688 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002689 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2690 // Synthesize a hover move event after all pointers go up to indicate that
2691 // the pointer is hovering again even if the user is not currently touching
2692 // the touch pad. This ensures that a view will receive a fresh hover enter
2693 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002694 float x, y;
2695 mPointerController->getPosition(&x, &y);
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 Pradhande69f8a2021-11-18 16:40:34 +00002901 float x, y;
2902 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002903
Michael Wright227c5542020-07-02 18:30:52 +01002904 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002905 mPointerGesture.currentGestureIdBits.clear();
2906 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2907 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2908 mPointerGesture.currentGestureProperties[0].clear();
2909 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2910 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2911 mPointerGesture.currentGestureCoords[0].clear();
2912 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2913 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2914 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2915 } else if (currentFingerCount == 0) {
2916 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002917 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002918 *outFinishPreviousGesture = true;
2919 }
2920
2921 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2922 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2923 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002924 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2925 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002926 lastFingerCount == 1) {
2927 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002928 float x, y;
2929 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002930 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2931 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002932 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002933
2934 mPointerGesture.tapUpTime = when;
2935 getContext()->requestTimeoutAtTime(when +
2936 mConfig.pointerGestureTapDragInterval);
2937
2938 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002939 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002940 mPointerGesture.currentGestureIdBits.clear();
2941 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2942 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2943 mPointerGesture.currentGestureProperties[0].clear();
2944 mPointerGesture.currentGestureProperties[0].id =
2945 mPointerGesture.activeGestureId;
2946 mPointerGesture.currentGestureProperties[0].toolType =
2947 AMOTION_EVENT_TOOL_TYPE_FINGER;
2948 mPointerGesture.currentGestureCoords[0].clear();
2949 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2950 mPointerGesture.tapX);
2951 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2952 mPointerGesture.tapY);
2953 mPointerGesture.currentGestureCoords[0]
2954 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2955
2956 tapped = true;
2957 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002958 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2959 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002960 }
2961 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002962 if (DEBUG_GESTURES) {
2963 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2964 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2965 (when - mPointerGesture.tapDownTime) * 0.000001f);
2966 } else {
2967 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2968 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002969 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002970 }
2971 }
2972
2973 mPointerVelocityControl.reset();
2974
2975 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002976 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002977 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002978 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002979 mPointerGesture.currentGestureIdBits.clear();
2980 }
2981 } else if (currentFingerCount == 1) {
2982 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2983 // The pointer follows the active touch point.
2984 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2985 // When in TAP_DRAG, emit MOVE events at the pointer location.
2986 ALOG_ASSERT(activeTouchId >= 0);
2987
Michael Wright227c5542020-07-02 18:30:52 +01002988 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2989 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002990 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002991 float x, y;
2992 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002993 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2994 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002995 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002996 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002997 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2998 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002999 }
3000 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003001 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3002 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003003 }
Michael Wright227c5542020-07-02 18:30:52 +01003004 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3005 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003006 }
3007
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003008 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003009 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003010 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003011 } else {
3012 mPointerVelocityControl.reset();
3013 }
3014
3015 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003016 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003017 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003018 down = true;
3019 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003020 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003021 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003022 *outFinishPreviousGesture = true;
3023 }
3024 mPointerGesture.activeGestureId = 0;
3025 down = false;
3026 }
3027
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003028 float x, y;
3029 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003030
3031 mPointerGesture.currentGestureIdBits.clear();
3032 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3033 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3034 mPointerGesture.currentGestureProperties[0].clear();
3035 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3036 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3037 mPointerGesture.currentGestureCoords[0].clear();
3038 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3039 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3040 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3041 down ? 1.0f : 0.0f);
3042
3043 if (lastFingerCount == 0 && currentFingerCount != 0) {
3044 mPointerGesture.resetTap();
3045 mPointerGesture.tapDownTime = when;
3046 mPointerGesture.tapX = x;
3047 mPointerGesture.tapY = y;
3048 }
3049 } else {
3050 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003051 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003052 }
3053
3054 mPointerController->setButtonState(mCurrentRawState.buttonState);
3055
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003056 if (DEBUG_GESTURES) {
3057 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3058 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3059 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3060 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3061 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3062 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3063 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3064 uint32_t id = idBits.clearFirstMarkedBit();
3065 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3066 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3067 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3068 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3069 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3070 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3071 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3072 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3073 }
3074 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3075 uint32_t id = idBits.clearFirstMarkedBit();
3076 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3077 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3078 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3079 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3080 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3081 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3082 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3083 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3084 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003085 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003086 return true;
3087}
3088
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003089bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3090 if (mPointerGesture.activeTouchId < 0) {
3091 mPointerGesture.resetQuietTime();
3092 return false;
3093 }
3094
3095 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3096 return true;
3097 }
3098
3099 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3100 bool isQuietTime = false;
3101 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3102 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3103 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3104 currentFingerCount < 2) {
3105 // Enter quiet time when exiting swipe or freeform state.
3106 // This is to prevent accidentally entering the hover state and flinging the
3107 // pointer when finishing a swipe and there is still one pointer left onscreen.
3108 isQuietTime = true;
3109 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3110 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3111 // Enter quiet time when releasing the button and there are still two or more
3112 // fingers down. This may indicate that one finger was used to press the button
3113 // but it has not gone up yet.
3114 isQuietTime = true;
3115 }
3116 if (isQuietTime) {
3117 mPointerGesture.quietTime = when;
3118 }
3119 return isQuietTime;
3120}
3121
3122std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3123 int32_t bestId = -1;
3124 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3125 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3126 uint32_t id = idBits.clearFirstMarkedBit();
3127 std::optional<float> vx =
3128 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3129 std::optional<float> vy =
3130 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3131 if (vx && vy) {
3132 float speed = hypotf(*vx, *vy);
3133 if (speed > bestSpeed) {
3134 bestId = id;
3135 bestSpeed = speed;
3136 }
3137 }
3138 }
3139 return std::make_pair(bestId, bestSpeed);
3140}
3141
3142void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3143 bool* finishPreviousGesture) {
3144 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3145 // to move before deciding what to do.
3146 //
3147 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3148 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3149 // just a press or long-press at the pointer location.
3150 //
3151 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3152 // pointer location.
3153 //
3154 // When the two fingers move enough or when additional fingers are added, we make a decision to
3155 // transition into SWIPE or FREEFORM mode accordingly.
3156 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3157 ALOG_ASSERT(activeTouchId >= 0);
3158
3159 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3160 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3161 bool settled =
3162 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3163 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3164 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3165 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3166 *finishPreviousGesture = true;
3167 } else if (!settled && currentFingerCount > lastFingerCount) {
3168 // Additional pointers have gone down but not yet settled.
3169 // Reset the gesture.
3170 ALOGD_IF(DEBUG_GESTURES,
3171 "Gestures: Resetting gesture since additional pointers went down for "
3172 "MULTITOUCH, settle time remaining %0.3fms",
3173 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3174 when) * 0.000001f);
3175 *cancelPreviousGesture = true;
3176 } else {
3177 // Continue previous gesture.
3178 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3179 }
3180
3181 if (*finishPreviousGesture || *cancelPreviousGesture) {
3182 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3183 mPointerGesture.activeGestureId = 0;
3184 mPointerGesture.referenceIdBits.clear();
3185 mPointerVelocityControl.reset();
3186
3187 // Use the centroid and pointer location as the reference points for the gesture.
3188 ALOGD_IF(DEBUG_GESTURES,
3189 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3190 "%0.3fms",
3191 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3192 when) * 0.000001f);
3193 mCurrentRawState.rawPointerData
3194 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3195 &mPointerGesture.referenceTouchY);
3196 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3197 &mPointerGesture.referenceGestureY);
3198 }
3199
3200 // Clear the reference deltas for fingers not yet included in the reference calculation.
3201 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3202 ~mPointerGesture.referenceIdBits.value);
3203 !idBits.isEmpty();) {
3204 uint32_t id = idBits.clearFirstMarkedBit();
3205 mPointerGesture.referenceDeltas[id].dx = 0;
3206 mPointerGesture.referenceDeltas[id].dy = 0;
3207 }
3208 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3209
3210 // Add delta for all fingers and calculate a common movement delta.
3211 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3212 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3213 mCurrentCookedState.fingerIdBits.value);
3214 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3215 bool first = (idBits == commonIdBits);
3216 uint32_t id = idBits.clearFirstMarkedBit();
3217 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3218 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3219 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3220 delta.dx += cpd.x - lpd.x;
3221 delta.dy += cpd.y - lpd.y;
3222
3223 if (first) {
3224 commonDeltaRawX = delta.dx;
3225 commonDeltaRawY = delta.dy;
3226 } else {
3227 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3228 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3229 }
3230 }
3231
3232 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3233 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3234 float dist[MAX_POINTER_ID + 1];
3235 int32_t distOverThreshold = 0;
3236 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3237 uint32_t id = idBits.clearFirstMarkedBit();
3238 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3239 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3240 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3241 distOverThreshold += 1;
3242 }
3243 }
3244
3245 // Only transition when at least two pointers have moved further than
3246 // the minimum distance threshold.
3247 if (distOverThreshold >= 2) {
3248 if (currentFingerCount > 2) {
3249 // There are more than two pointers, switch to FREEFORM.
3250 ALOGD_IF(DEBUG_GESTURES,
3251 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3252 currentFingerCount);
3253 *cancelPreviousGesture = true;
3254 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3255 } else {
3256 // There are exactly two pointers.
3257 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3258 uint32_t id1 = idBits.clearFirstMarkedBit();
3259 uint32_t id2 = idBits.firstMarkedBit();
3260 const RawPointerData::Pointer& p1 =
3261 mCurrentRawState.rawPointerData.pointerForId(id1);
3262 const RawPointerData::Pointer& p2 =
3263 mCurrentRawState.rawPointerData.pointerForId(id2);
3264 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3265 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3266 // There are two pointers but they are too far apart for a SWIPE,
3267 // switch to FREEFORM.
3268 ALOGD_IF(DEBUG_GESTURES,
3269 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3270 mutualDistance, mPointerGestureMaxSwipeWidth);
3271 *cancelPreviousGesture = true;
3272 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3273 } else {
3274 // There are two pointers. Wait for both pointers to start moving
3275 // before deciding whether this is a SWIPE or FREEFORM gesture.
3276 float dist1 = dist[id1];
3277 float dist2 = dist[id2];
3278 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3279 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3280 // Calculate the dot product of the displacement vectors.
3281 // When the vectors are oriented in approximately the same direction,
3282 // the angle betweeen them is near zero and the cosine of the angle
3283 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3284 // mag(v2).
3285 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3286 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3287 float dx1 = delta1.dx * mPointerXZoomScale;
3288 float dy1 = delta1.dy * mPointerYZoomScale;
3289 float dx2 = delta2.dx * mPointerXZoomScale;
3290 float dy2 = delta2.dy * mPointerYZoomScale;
3291 float dot = dx1 * dx2 + dy1 * dy2;
3292 float cosine = dot / (dist1 * dist2); // denominator always > 0
3293 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3294 // Pointers are moving in the same direction. Switch to SWIPE.
3295 ALOGD_IF(DEBUG_GESTURES,
3296 "Gestures: PRESS transitioned to SWIPE, "
3297 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3298 "cosine %0.3f >= %0.3f",
3299 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3300 mConfig.pointerGestureMultitouchMinDistance, cosine,
3301 mConfig.pointerGestureSwipeTransitionAngleCosine);
3302 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3303 } else {
3304 // Pointers are moving in different directions. Switch to FREEFORM.
3305 ALOGD_IF(DEBUG_GESTURES,
3306 "Gestures: PRESS transitioned to FREEFORM, "
3307 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3308 "cosine %0.3f < %0.3f",
3309 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3310 mConfig.pointerGestureMultitouchMinDistance, cosine,
3311 mConfig.pointerGestureSwipeTransitionAngleCosine);
3312 *cancelPreviousGesture = true;
3313 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3314 }
3315 }
3316 }
3317 }
3318 }
3319 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3320 // Switch from SWIPE to FREEFORM if additional pointers go down.
3321 // Cancel previous gesture.
3322 if (currentFingerCount > 2) {
3323 ALOGD_IF(DEBUG_GESTURES,
3324 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3325 currentFingerCount);
3326 *cancelPreviousGesture = true;
3327 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3328 }
3329 }
3330
3331 // Move the reference points based on the overall group motion of the fingers
3332 // except in PRESS mode while waiting for a transition to occur.
3333 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3334 (commonDeltaRawX || commonDeltaRawY)) {
3335 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3336 uint32_t id = idBits.clearFirstMarkedBit();
3337 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3338 delta.dx = 0;
3339 delta.dy = 0;
3340 }
3341
3342 mPointerGesture.referenceTouchX += commonDeltaRawX;
3343 mPointerGesture.referenceTouchY += commonDeltaRawY;
3344
3345 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3346 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3347
3348 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3349 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3350
3351 mPointerGesture.referenceGestureX += commonDeltaX;
3352 mPointerGesture.referenceGestureY += commonDeltaY;
3353 }
3354
3355 // Report gestures.
3356 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3357 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3358 // PRESS or SWIPE mode.
3359 ALOGD_IF(DEBUG_GESTURES,
3360 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3361 "currentTouchPointerCount=%d",
3362 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3363 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3364
3365 mPointerGesture.currentGestureIdBits.clear();
3366 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3367 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3368 mPointerGesture.currentGestureProperties[0].clear();
3369 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3370 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3371 mPointerGesture.currentGestureCoords[0].clear();
3372 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3373 mPointerGesture.referenceGestureX);
3374 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3375 mPointerGesture.referenceGestureY);
3376 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3377 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3378 float xOffset = static_cast<float>(commonDeltaRawX) /
3379 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3380 float yOffset = static_cast<float>(commonDeltaRawY) /
3381 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3382 mPointerGesture.currentGestureCoords[0]
3383 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3384 mPointerGesture.currentGestureCoords[0]
3385 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3386 }
3387 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3388 // FREEFORM mode.
3389 ALOGD_IF(DEBUG_GESTURES,
3390 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3391 "currentTouchPointerCount=%d",
3392 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3393 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3394
3395 mPointerGesture.currentGestureIdBits.clear();
3396
3397 BitSet32 mappedTouchIdBits;
3398 BitSet32 usedGestureIdBits;
3399 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3400 // Initially, assign the active gesture id to the active touch point
3401 // if there is one. No other touch id bits are mapped yet.
3402 if (!*cancelPreviousGesture) {
3403 mappedTouchIdBits.markBit(activeTouchId);
3404 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3405 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3406 mPointerGesture.activeGestureId;
3407 } else {
3408 mPointerGesture.activeGestureId = -1;
3409 }
3410 } else {
3411 // Otherwise, assume we mapped all touches from the previous frame.
3412 // Reuse all mappings that are still applicable.
3413 mappedTouchIdBits.value =
3414 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3415 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3416
3417 // Check whether we need to choose a new active gesture id because the
3418 // current went went up.
3419 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3420 ~mCurrentCookedState.fingerIdBits.value);
3421 !upTouchIdBits.isEmpty();) {
3422 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3423 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3424 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3425 mPointerGesture.activeGestureId = -1;
3426 break;
3427 }
3428 }
3429 }
3430
3431 ALOGD_IF(DEBUG_GESTURES,
3432 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3433 "activeGestureId=%d",
3434 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3435
3436 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3437 for (uint32_t i = 0; i < currentFingerCount; i++) {
3438 uint32_t touchId = idBits.clearFirstMarkedBit();
3439 uint32_t gestureId;
3440 if (!mappedTouchIdBits.hasBit(touchId)) {
3441 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3442 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3443 ALOGD_IF(DEBUG_GESTURES,
3444 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3445 gestureId);
3446 } else {
3447 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3448 ALOGD_IF(DEBUG_GESTURES,
3449 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3450 touchId, gestureId);
3451 }
3452 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3453 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3454
3455 const RawPointerData::Pointer& pointer =
3456 mCurrentRawState.rawPointerData.pointerForId(touchId);
3457 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3458 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3459 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3460
3461 mPointerGesture.currentGestureProperties[i].clear();
3462 mPointerGesture.currentGestureProperties[i].id = gestureId;
3463 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3464 mPointerGesture.currentGestureCoords[i].clear();
3465 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3466 mPointerGesture.referenceGestureX +
3467 deltaX);
3468 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3469 mPointerGesture.referenceGestureY +
3470 deltaY);
3471 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3472 }
3473
3474 if (mPointerGesture.activeGestureId < 0) {
3475 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3476 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3477 mPointerGesture.activeGestureId);
3478 }
3479 }
3480}
3481
Harry Cutts714d1ad2022-08-24 16:36:43 +00003482void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3483 const RawPointerData::Pointer& currentPointer =
3484 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3485 const RawPointerData::Pointer& lastPointer =
3486 mLastRawState.rawPointerData.pointerForId(pointerId);
3487 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3488 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3489
3490 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3491 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3492
3493 mPointerController->move(deltaX, deltaY);
3494}
3495
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003496std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3497 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003498 mPointerSimple.currentCoords.clear();
3499 mPointerSimple.currentProperties.clear();
3500
3501 bool down, hovering;
3502 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3503 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3504 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003505 mPointerController
3506 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3507 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003508
3509 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3510 down = !hovering;
3511
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003512 float x, y;
3513 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003514 mPointerSimple.currentCoords.copyFrom(
3515 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3516 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3517 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3518 mPointerSimple.currentProperties.id = 0;
3519 mPointerSimple.currentProperties.toolType =
3520 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3521 } else {
3522 down = false;
3523 hovering = false;
3524 }
3525
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003526 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003527}
3528
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003529std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3530 uint32_t policyFlags) {
3531 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003532}
3533
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003534std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3535 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003536 mPointerSimple.currentCoords.clear();
3537 mPointerSimple.currentProperties.clear();
3538
3539 bool down, hovering;
3540 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3541 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003542 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003543 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003544 } else {
3545 mPointerVelocityControl.reset();
3546 }
3547
3548 down = isPointerDown(mCurrentRawState.buttonState);
3549 hovering = !down;
3550
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003551 float x, y;
3552 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003553 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003554 mPointerSimple.currentCoords.copyFrom(
3555 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3556 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3557 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3558 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3559 hovering ? 0.0f : 1.0f);
3560 mPointerSimple.currentProperties.id = 0;
3561 mPointerSimple.currentProperties.toolType =
3562 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3563 } else {
3564 mPointerVelocityControl.reset();
3565
3566 down = false;
3567 hovering = false;
3568 }
3569
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003570 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003571}
3572
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003573std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3574 uint32_t policyFlags) {
3575 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003576
3577 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003578
3579 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003580}
3581
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003582std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3583 uint32_t policyFlags, bool down,
3584 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003585 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3586 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003587 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003588 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003589
3590 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003591 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003592 mPointerController->clearSpots();
3593 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003594 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003595 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003596 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003597 }
Garfield Tan9514d782020-11-10 16:37:23 -08003598 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003599
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003600 float xCursorPosition, yCursorPosition;
3601 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003602
3603 if (mPointerSimple.down && !down) {
3604 mPointerSimple.down = false;
3605
3606 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003607 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3608 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3609 0, metaState, mLastRawState.buttonState,
3610 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3611 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3612 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3613 yCursorPosition, mPointerSimple.downTime,
3614 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003615 }
3616
3617 if (mPointerSimple.hovering && !hovering) {
3618 mPointerSimple.hovering = false;
3619
3620 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003621 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3622 mSource, displayId, policyFlags,
3623 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3624 mLastRawState.buttonState, MotionClassification::NONE,
3625 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3626 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3627 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3628 yCursorPosition, mPointerSimple.downTime,
3629 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003630 }
3631
3632 if (down) {
3633 if (!mPointerSimple.down) {
3634 mPointerSimple.down = true;
3635 mPointerSimple.downTime = when;
3636
3637 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003638 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3639 mSource, displayId, policyFlags,
3640 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3641 mCurrentRawState.buttonState, MotionClassification::NONE,
3642 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3643 &mPointerSimple.currentProperties,
3644 &mPointerSimple.currentCoords, mOrientedXPrecision,
3645 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3646 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003647 }
3648
3649 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003650 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3651 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3652 0, 0, metaState, mCurrentRawState.buttonState,
3653 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3654 &mPointerSimple.currentProperties,
3655 &mPointerSimple.currentCoords, mOrientedXPrecision,
3656 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3657 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003658 }
3659
3660 if (hovering) {
3661 if (!mPointerSimple.hovering) {
3662 mPointerSimple.hovering = true;
3663
3664 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003665 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3666 mSource, displayId, policyFlags,
3667 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3668 mCurrentRawState.buttonState, MotionClassification::NONE,
3669 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3670 &mPointerSimple.currentProperties,
3671 &mPointerSimple.currentCoords, mOrientedXPrecision,
3672 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3673 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003674 }
3675
3676 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003677 out.push_back(
3678 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3679 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3680 metaState, mCurrentRawState.buttonState,
3681 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3682 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3683 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3684 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003685 }
3686
3687 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3688 float vscroll = mCurrentRawState.rawVScroll;
3689 float hscroll = mCurrentRawState.rawHScroll;
3690 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3691 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3692
3693 // Send scroll.
3694 PointerCoords pointerCoords;
3695 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3696 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3697 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3698
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003699 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3700 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3701 0, 0, metaState, mCurrentRawState.buttonState,
3702 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3703 &mPointerSimple.currentProperties, &pointerCoords,
3704 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3705 yCursorPosition, mPointerSimple.downTime,
3706 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003707 }
3708
3709 // Save state.
3710 if (down || hovering) {
3711 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3712 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003713 mPointerSimple.displayId = displayId;
3714 mPointerSimple.source = mSource;
3715 mPointerSimple.lastCursorX = xCursorPosition;
3716 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003717 } else {
3718 mPointerSimple.reset();
3719 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003720 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003721}
3722
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003723std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3724 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003725 std::list<NotifyArgs> out;
3726 if (mPointerSimple.down || mPointerSimple.hovering) {
3727 int32_t metaState = getContext()->getGlobalMetaState();
3728 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3729 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3730 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3731 metaState, mLastRawState.buttonState,
3732 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3733 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3734 mOrientedXPrecision, mOrientedYPrecision,
3735 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3736 mPointerSimple.downTime,
3737 /* videoFrames */ {}));
3738 if (mPointerController != nullptr) {
3739 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3740 }
3741 }
3742 mPointerSimple.reset();
3743 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003744}
3745
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003746static bool isStylusEvent(uint32_t source, int32_t action, const PointerProperties* properties) {
3747 if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
3748 return false;
3749 }
3750 const auto actionIndex = action >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3751 return isStylusToolType(properties[actionIndex].toolType);
3752}
3753
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003754NotifyMotionArgs TouchInputMapper::dispatchMotion(
3755 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3756 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003757 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3758 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003759 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003760 PointerCoords pointerCoords[MAX_POINTERS];
3761 PointerProperties pointerProperties[MAX_POINTERS];
3762 uint32_t pointerCount = 0;
3763 while (!idBits.isEmpty()) {
3764 uint32_t id = idBits.clearFirstMarkedBit();
3765 uint32_t index = idToIndex[id];
3766 pointerProperties[pointerCount].copyFrom(properties[index]);
3767 pointerCoords[pointerCount].copyFrom(coords[index]);
3768
3769 if (changedId >= 0 && id == uint32_t(changedId)) {
3770 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3771 }
3772
3773 pointerCount += 1;
3774 }
3775
3776 ALOG_ASSERT(pointerCount != 0);
3777
3778 if (changedId >= 0 && pointerCount == 1) {
3779 // Replace initial down and final up action.
3780 // We can compare the action without masking off the changed pointer index
3781 // because we know the index is 0.
3782 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3783 action = AMOTION_EVENT_ACTION_DOWN;
3784 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003785 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3786 action = AMOTION_EVENT_ACTION_CANCEL;
3787 } else {
3788 action = AMOTION_EVENT_ACTION_UP;
3789 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003790 } else {
3791 // Can't happen.
3792 ALOG_ASSERT(false);
3793 }
3794 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003795
3796 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3797 const bool showDirectStylusPointer = mConfig.stylusPointerIconEnabled &&
3798 mDeviceMode == DeviceMode::DIRECT && isStylusEvent(source, action, pointerProperties) &&
Seunghwan Choi356026c2023-02-01 14:37:25 +09003799 mPointerController && displayId != ADISPLAY_ID_NONE &&
3800 displayId == mPointerController->getDisplayId();
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003801 if (showDirectStylusPointer) {
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003802 switch (action & AMOTION_EVENT_ACTION_MASK) {
3803 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3804 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3805 mPointerController->setPresentation(
Seunghwan Choi75789cd2023-01-13 20:31:59 +09003806 PointerControllerInterface::Presentation::STYLUS_HOVER);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003807 mPointerController
3808 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[0].getX(),
3809 mCurrentCookedState.cookedPointerData.pointerCoords[0]
3810 .getY());
3811 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3812 break;
3813 case AMOTION_EVENT_ACTION_HOVER_EXIT:
3814 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
3815 break;
3816 }
3817 }
3818
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003819 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3820 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003821 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003822 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003823 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003824 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003825 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003826 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003827 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003828 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3829 policyFlags, action, actionButton, flags, metaState, buttonState,
3830 classification, edgeFlags, pointerCount, pointerProperties,
3831 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3832 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003833}
3834
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003835std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3836 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003837 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3838 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003839 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003840}
3841
Prabir Pradhan1728b212021-10-19 16:00:03 -07003842bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003843 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003844 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003845 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003846}
3847
3848const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3849 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003850 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3851 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3852 "left=%d, top=%d, right=%d, bottom=%d",
3853 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3854 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003855
3856 if (virtualKey.isHit(x, y)) {
3857 return &virtualKey;
3858 }
3859 }
3860
3861 return nullptr;
3862}
3863
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003864void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3865 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3866 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003867
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003868 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003869
3870 if (currentPointerCount == 0) {
3871 // No pointers to assign.
3872 return;
3873 }
3874
3875 if (lastPointerCount == 0) {
3876 // All pointers are new.
3877 for (uint32_t i = 0; i < currentPointerCount; i++) {
3878 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003879 current.rawPointerData.pointers[i].id = id;
3880 current.rawPointerData.idToIndex[id] = i;
3881 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003882 }
3883 return;
3884 }
3885
3886 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003887 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003888 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003889 uint32_t id = last.rawPointerData.pointers[0].id;
3890 current.rawPointerData.pointers[0].id = id;
3891 current.rawPointerData.idToIndex[id] = 0;
3892 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003893 return;
3894 }
3895
3896 // General case.
3897 // We build a heap of squared euclidean distances between current and last pointers
3898 // associated with the current and last pointer indices. Then, we find the best
3899 // match (by distance) for each current pointer.
3900 // The pointers must have the same tool type but it is possible for them to
3901 // transition from hovering to touching or vice-versa while retaining the same id.
3902 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3903
3904 uint32_t heapSize = 0;
3905 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3906 currentPointerIndex++) {
3907 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3908 lastPointerIndex++) {
3909 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003910 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003911 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003912 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003913 if (currentPointer.toolType == lastPointer.toolType) {
3914 int64_t deltaX = currentPointer.x - lastPointer.x;
3915 int64_t deltaY = currentPointer.y - lastPointer.y;
3916
3917 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3918
3919 // Insert new element into the heap (sift up).
3920 heap[heapSize].currentPointerIndex = currentPointerIndex;
3921 heap[heapSize].lastPointerIndex = lastPointerIndex;
3922 heap[heapSize].distance = distance;
3923 heapSize += 1;
3924 }
3925 }
3926 }
3927
3928 // Heapify
3929 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3930 startIndex -= 1;
3931 for (uint32_t parentIndex = startIndex;;) {
3932 uint32_t childIndex = parentIndex * 2 + 1;
3933 if (childIndex >= heapSize) {
3934 break;
3935 }
3936
3937 if (childIndex + 1 < heapSize &&
3938 heap[childIndex + 1].distance < heap[childIndex].distance) {
3939 childIndex += 1;
3940 }
3941
3942 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3943 break;
3944 }
3945
3946 swap(heap[parentIndex], heap[childIndex]);
3947 parentIndex = childIndex;
3948 }
3949 }
3950
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003951 if (DEBUG_POINTER_ASSIGNMENT) {
3952 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3953 for (size_t i = 0; i < heapSize; i++) {
3954 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3955 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3956 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003957 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003958
3959 // Pull matches out by increasing order of distance.
3960 // To avoid reassigning pointers that have already been matched, the loop keeps track
3961 // of which last and current pointers have been matched using the matchedXXXBits variables.
3962 // It also tracks the used pointer id bits.
3963 BitSet32 matchedLastBits(0);
3964 BitSet32 matchedCurrentBits(0);
3965 BitSet32 usedIdBits(0);
3966 bool first = true;
3967 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3968 while (heapSize > 0) {
3969 if (first) {
3970 // The first time through the loop, we just consume the root element of
3971 // the heap (the one with smallest distance).
3972 first = false;
3973 } else {
3974 // Previous iterations consumed the root element of the heap.
3975 // Pop root element off of the heap (sift down).
3976 heap[0] = heap[heapSize];
3977 for (uint32_t parentIndex = 0;;) {
3978 uint32_t childIndex = parentIndex * 2 + 1;
3979 if (childIndex >= heapSize) {
3980 break;
3981 }
3982
3983 if (childIndex + 1 < heapSize &&
3984 heap[childIndex + 1].distance < heap[childIndex].distance) {
3985 childIndex += 1;
3986 }
3987
3988 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3989 break;
3990 }
3991
3992 swap(heap[parentIndex], heap[childIndex]);
3993 parentIndex = childIndex;
3994 }
3995
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003996 if (DEBUG_POINTER_ASSIGNMENT) {
3997 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3998 for (size_t j = 0; j < heapSize; j++) {
3999 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
4000 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4001 heap[j].distance);
4002 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004003 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004004 }
4005
4006 heapSize -= 1;
4007
4008 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4009 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4010
4011 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4012 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4013
4014 matchedCurrentBits.markBit(currentPointerIndex);
4015 matchedLastBits.markBit(lastPointerIndex);
4016
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004017 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4018 current.rawPointerData.pointers[currentPointerIndex].id = id;
4019 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4020 current.rawPointerData.markIdBit(id,
4021 current.rawPointerData.isHovering(
4022 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004023 usedIdBits.markBit(id);
4024
Harry Cutts45483602022-08-24 14:36:48 +00004025 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4026 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4027 ", distance=%" PRIu64,
4028 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004029 break;
4030 }
4031 }
4032
4033 // Assign fresh ids to pointers that were not matched in the process.
4034 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4035 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4036 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4037
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004038 current.rawPointerData.pointers[currentPointerIndex].id = id;
4039 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4040 current.rawPointerData.markIdBit(id,
4041 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004042
Harry Cutts45483602022-08-24 14:36:48 +00004043 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4044 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4045 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004046 }
4047}
4048
4049int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4050 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4051 return AKEY_STATE_VIRTUAL;
4052 }
4053
4054 for (const VirtualKey& virtualKey : mVirtualKeys) {
4055 if (virtualKey.keyCode == keyCode) {
4056 return AKEY_STATE_UP;
4057 }
4058 }
4059
4060 return AKEY_STATE_UNKNOWN;
4061}
4062
4063int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4064 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4065 return AKEY_STATE_VIRTUAL;
4066 }
4067
4068 for (const VirtualKey& virtualKey : mVirtualKeys) {
4069 if (virtualKey.scanCode == scanCode) {
4070 return AKEY_STATE_UP;
4071 }
4072 }
4073
4074 return AKEY_STATE_UNKNOWN;
4075}
4076
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004077bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4078 const std::vector<int32_t>& keyCodes,
4079 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004080 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004081 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004082 if (virtualKey.keyCode == keyCodes[i]) {
4083 outFlags[i] = 1;
4084 }
4085 }
4086 }
4087
4088 return true;
4089}
4090
4091std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4092 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004093 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004094 return std::make_optional(mPointerController->getDisplayId());
4095 } else {
4096 return std::make_optional(mViewport.displayId);
4097 }
4098 }
4099 return std::nullopt;
4100}
4101
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004102} // namespace android