blob: b53fc7399a4f60782049f8015e15336675edc2c2 [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Michael Wright227c5542020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wright227c5542020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
21#include "TouchInputMapper.h"
22
Dominik Laskowski75788452021-02-09 18:51:25 -080023#include <ftl/enum.h>
Prabir Pradhan8d9ba912022-11-11 22:26:33 +000024#include <input/PrintTools.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080025
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070026#include "CursorButtonAccumulator.h"
27#include "CursorScrollAccumulator.h"
28#include "TouchButtonAccumulator.h"
29#include "TouchCursorInputMapperCommon.h"
Michael Wrighta9cf4192022-12-01 23:46:39 +000030#include "ui/Rotation.h"
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070031
32namespace android {
33
34// --- Constants ---
35
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070036// Artificial latency on synthetic events created from stylus data without corresponding touch
37// data.
38static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
39
HQ Liue6983c72022-04-19 22:14:56 +000040// Minimum width between two pointers to determine a gesture as freeform gesture in mm
41static const float MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER = 30;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070042// --- Static Definitions ---
43
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +000044static const DisplayViewport kUninitializedViewport;
45
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000046static std::string toString(const Rect& rect) {
47 return base::StringPrintf("Rect{%d, %d, %d, %d}", rect.left, rect.top, rect.right, rect.bottom);
48}
49
50static std::string toString(const ui::Size& size) {
51 return base::StringPrintf("%dx%d", size.width, size.height);
52}
53
Prabir Pradhan675f25a2022-11-10 22:04:07 +000054static bool isPointInRect(const Rect& rect, vec2 p) {
55 return p.x >= rect.left && p.x < rect.right && p.y >= rect.top && p.y < rect.bottom;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000056}
57
Prabir Pradhane04ffaa2022-12-13 23:04:04 +000058static std::string toString(const InputDeviceUsiVersion& v) {
59 return base::StringPrintf("%d.%d", v.majorVersion, v.minorVersion);
60}
61
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070062template <typename T>
63inline static void swap(T& a, T& b) {
64 T temp = a;
65 a = b;
66 b = temp;
67}
68
69static float calculateCommonVector(float a, float b) {
70 if (a > 0 && b > 0) {
71 return a < b ? a : b;
72 } else if (a < 0 && b < 0) {
73 return a > b ? a : b;
74 } else {
75 return 0;
76 }
77}
78
79inline static float distance(float x1, float y1, float x2, float y2) {
80 return hypotf(x1 - x2, y1 - y2);
81}
82
83inline static int32_t signExtendNybble(int32_t value) {
84 return value >= 8 ? value - 16 : value;
85}
86
Prabir Pradhan675f25a2022-11-10 22:04:07 +000087static ui::Size getNaturalDisplaySize(const DisplayViewport& viewport) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000088 ui::Size rotatedDisplaySize{viewport.deviceWidth, viewport.deviceHeight};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +000089 if (viewport.orientation == ui::ROTATION_90 || viewport.orientation == ui::ROTATION_270) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000090 std::swap(rotatedDisplaySize.width, rotatedDisplaySize.height);
91 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +000092 return rotatedDisplaySize;
Prabir Pradhan2d613f42022-11-10 20:22:06 +000093}
94
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +000095static int32_t filterButtonState(InputReaderConfiguration& config, int32_t buttonState) {
96 if (!config.stylusButtonMotionEventsEnabled) {
97 buttonState &=
98 ~(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY | AMOTION_EVENT_BUTTON_STYLUS_SECONDARY);
99 }
100 return buttonState;
101}
102
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700103// --- RawPointerData ---
104
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700105void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
106 float x = 0, y = 0;
107 uint32_t count = touchingIdBits.count();
108 if (count) {
109 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
110 uint32_t id = idBits.clearFirstMarkedBit();
111 const Pointer& pointer = pointerForId(id);
112 x += pointer.x;
113 y += pointer.y;
114 }
115 x /= count;
116 y /= count;
117 }
118 *outX = x;
119 *outY = y;
120}
121
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700122// --- TouchInputMapper ---
123
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800124TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
125 : InputMapper(deviceContext),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000126 mTouchButtonAccumulator(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700127 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100128 mDeviceMode(DeviceMode::DISABLED),
Michael Wrighta9cf4192022-12-01 23:46:39 +0000129 mInputDeviceOrientation(ui::ROTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700130
131TouchInputMapper::~TouchInputMapper() {}
132
Philip Junker4af3b3d2021-12-14 10:36:55 +0100133uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700134 return mSource;
135}
136
137void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
138 InputMapper::populateDeviceInfo(info);
139
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000140 if (mDeviceMode == DeviceMode::DISABLED) {
141 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700142 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000143
144 info->addMotionRange(mOrientedRanges.x);
145 info->addMotionRange(mOrientedRanges.y);
146 info->addMotionRange(mOrientedRanges.pressure);
147
148 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
149 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
150 //
151 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
152 // motion, i.e. the hardware dimensions, as the finger could move completely across the
153 // touchpad in one sample cycle.
154 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
155 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
156 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
157 x.resolution);
158 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
159 y.resolution);
160 }
161
162 if (mOrientedRanges.size) {
163 info->addMotionRange(*mOrientedRanges.size);
164 }
165
166 if (mOrientedRanges.touchMajor) {
167 info->addMotionRange(*mOrientedRanges.touchMajor);
168 info->addMotionRange(*mOrientedRanges.touchMinor);
169 }
170
171 if (mOrientedRanges.toolMajor) {
172 info->addMotionRange(*mOrientedRanges.toolMajor);
173 info->addMotionRange(*mOrientedRanges.toolMinor);
174 }
175
176 if (mOrientedRanges.orientation) {
177 info->addMotionRange(*mOrientedRanges.orientation);
178 }
179
180 if (mOrientedRanges.distance) {
181 info->addMotionRange(*mOrientedRanges.distance);
182 }
183
184 if (mOrientedRanges.tilt) {
185 info->addMotionRange(*mOrientedRanges.tilt);
186 }
187
188 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
189 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
190 }
191 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
192 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
193 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000194 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000195 info->setUsiVersion(mParameters.usiVersion);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700196}
197
198void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700199 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800200 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700201 dumpParameters(dump);
202 dumpVirtualKeys(dump);
203 dumpRawPointerAxes(dump);
204 dumpCalibration(dump);
205 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700206 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700207
208 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000209 mRawToDisplay.dump(dump, "RawToDisplay Transform:", INDENT4);
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000210 mRawRotation.dump(dump, "RawRotation Transform:", INDENT4);
211 dump += StringPrintf(INDENT4 "OrientedXPrecision: %0.3f\n", mOrientedXPrecision);
212 dump += StringPrintf(INDENT4 "OrientedYPrecision: %0.3f\n", mOrientedYPrecision);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700213 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
214 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
215 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
216 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
217 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
218 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
219 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
220 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
221 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
222 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
223
224 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
225 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
226 mLastRawState.rawPointerData.pointerCount);
227 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
228 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
229 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
230 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
231 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
232 "toolType=%d, isHovering=%s\n",
233 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
234 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
235 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
236 pointer.distance, pointer.toolType, toString(pointer.isHovering));
237 }
238
239 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
240 mLastCookedState.buttonState);
241 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
242 mLastCookedState.cookedPointerData.pointerCount);
243 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
244 const PointerProperties& pointerProperties =
245 mLastCookedState.cookedPointerData.pointerProperties[i];
246 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000247 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
248 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
249 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700250 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
251 "toolType=%d, isHovering=%s\n",
252 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000253 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
254 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700255 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
256 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
257 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
258 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
259 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
260 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
261 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
262 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
263 pointerProperties.toolType,
264 toString(mLastCookedState.cookedPointerData.isHovering(i)));
265 }
266
267 dump += INDENT3 "Stylus Fusion:\n";
268 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
269 toString(mExternalStylusConnected));
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000270 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
271 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700272 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
273 mExternalStylusFusionTimeout);
Prabir Pradhan124ea442022-10-28 20:27:44 +0000274 dump += StringPrintf(INDENT4 " External Stylus Buttons Applied: 0x%08x",
275 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700276 dump += INDENT3 "External Stylus State:\n";
277 dumpStylusState(dump, mExternalStylusState);
278
Michael Wright227c5542020-07-02 18:30:52 +0100279 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700280 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
281 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
282 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
283 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
284 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
285 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
286 }
287}
288
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700289std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
290 const InputReaderConfiguration* config,
291 uint32_t changes) {
292 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700293
294 mConfig = *config;
295
Ambrus Weisz7b6e16b2022-12-16 17:54:57 +0000296 // Full configuration should happen the first time configure is called and
297 // when the device type is changed. Changing a device type can affect
298 // various other parameters so should result in a reconfiguration.
299 if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_TYPE)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700300 // Configure basic parameters.
301 configureParameters();
302
303 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800304 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000305 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700306
307 // Configure absolute axis information.
308 configureRawPointerAxes();
309
310 // Prepare input device calibration.
311 parseCalibration();
312 resolveCalibration();
313 }
314
315 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
316 // Update location calibration to reflect current settings
317 updateAffineTransformation();
318 }
319
320 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
321 // Update pointer speed.
322 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
323 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
324 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
325 }
326
327 bool resetNeeded = false;
328 if (!changes ||
329 (changes &
330 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800331 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700332 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
333 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
Ambrus Weisz7b6e16b2022-12-16 17:54:57 +0000334 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE |
335 InputReaderConfiguration::CHANGE_DEVICE_TYPE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700336 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700337 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700338 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700339 }
340
341 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700342 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000343
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700344 // Send reset, unless this is the first time the device has been configured,
345 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000346 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700347 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700348 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700349}
350
351void TouchInputMapper::resolveExternalStylusPresence() {
352 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800353 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700354 mExternalStylusConnected = !devices.empty();
355
356 if (!mExternalStylusConnected) {
357 resetExternalStylus();
358 }
359}
360
361void TouchInputMapper::configureParameters() {
362 // Use the pointer presentation mode for devices that do not support distinct
363 // multitouch. The spot-based presentation relies on being able to accurately
364 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800365 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100366 ? Parameters::GestureMode::SINGLE_TOUCH
367 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700368
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700369 std::string gestureModeString;
370 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800371 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700372 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100373 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700374 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100375 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700376 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700377 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700378 }
379 }
380
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000381 configureDeviceType();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700382
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800383 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700384
Michael Wright227c5542020-07-02 18:30:52 +0100385 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700386 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800387 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700388
Michael Wrighta9cf4192022-12-01 23:46:39 +0000389 mParameters.orientation = ui::ROTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700390 std::string orientationString;
391 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700392 orientationString)) {
393 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
394 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
395 } else if (orientationString == "ORIENTATION_90") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000396 mParameters.orientation = ui::ROTATION_90;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700397 } else if (orientationString == "ORIENTATION_180") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000398 mParameters.orientation = ui::ROTATION_180;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700399 } else if (orientationString == "ORIENTATION_270") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000400 mParameters.orientation = ui::ROTATION_270;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700401 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700402 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700403 }
404 }
405
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700406 mParameters.hasAssociatedDisplay = false;
407 mParameters.associatedDisplayIsExternal = false;
408 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100409 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000410 mParameters.deviceType == Parameters::DeviceType::POINTER ||
411 (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
412 getDeviceContext().getAssociatedViewport())) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700413 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100414 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800415 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700416 std::string uniqueDisplayId;
417 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800418 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700419 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
420 }
421 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800422 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700423 mParameters.hasAssociatedDisplay = true;
424 }
425
426 // Initial downs on external touch devices should wake the device.
427 // Normally we don't do this for internal touch screens to prevent them from waking
428 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800429 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700430 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000431
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000432 InputDeviceUsiVersion usiVersion;
433 if (getDeviceContext().getConfiguration().tryGetProperty("touch.usiVersionMajor",
434 usiVersion.majorVersion) &&
435 getDeviceContext().getConfiguration().tryGetProperty("touch.usiVersionMinor",
436 usiVersion.minorVersion)) {
437 mParameters.usiVersion = usiVersion;
438 }
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700439
440 mParameters.enableForInactiveViewport = false;
441 getDeviceContext().getConfiguration().tryGetProperty("touch.enableForInactiveViewport",
442 mParameters.enableForInactiveViewport);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700443}
444
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000445void TouchInputMapper::configureDeviceType() {
446 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
447 // The device is a touch screen.
448 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
449 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
450 // The device is a pointing device like a track pad.
451 mParameters.deviceType = Parameters::DeviceType::POINTER;
452 } else {
453 // The device is a touch pad of unknown purpose.
454 mParameters.deviceType = Parameters::DeviceType::POINTER;
455 }
456
457 // Type association takes precedence over the device type found in the idc file.
458 std::string deviceTypeString = getDeviceContext().getDeviceTypeAssociation().value_or("");
459 if (deviceTypeString.empty()) {
460 getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType", deviceTypeString);
461 }
462 if (deviceTypeString == "touchScreen") {
463 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
464 } else if (deviceTypeString == "touchNavigation") {
465 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
466 } else if (deviceTypeString == "pointer") {
467 mParameters.deviceType = Parameters::DeviceType::POINTER;
468 } else if (deviceTypeString != "default" && deviceTypeString != "") {
469 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
470 }
471}
472
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700473void TouchInputMapper::dumpParameters(std::string& dump) {
474 dump += INDENT3 "Parameters:\n";
475
Dominik Laskowski75788452021-02-09 18:51:25 -0800476 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700477
Dominik Laskowski75788452021-02-09 18:51:25 -0800478 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700479
480 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
481 "displayId='%s'\n",
482 toString(mParameters.hasAssociatedDisplay),
483 toString(mParameters.associatedDisplayIsExternal),
484 mParameters.uniqueDisplayId.c_str());
485 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800486 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000487 dump += StringPrintf(INDENT4 "UsiVersion: %s\n",
488 toString(mParameters.usiVersion, toString).c_str());
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700489 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
490 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700491}
492
493void TouchInputMapper::configureRawPointerAxes() {
494 mRawPointerAxes.clear();
495}
496
497void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
498 dump += INDENT3 "Raw Touch Axes:\n";
499 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
500 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
501 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
502 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
503 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
504 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
505 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
506 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
507 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
508 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
509 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
510 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
511 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
512}
513
514bool TouchInputMapper::hasExternalStylus() const {
515 return mExternalStylusConnected;
516}
517
518/**
519 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000520 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800521 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000522 * 3. Get the matching viewport by either unique id in idc file or by the display type
523 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800524 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700525 */
526std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800527 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000528 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800529 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700530 }
531
Christine Franks2a2293c2022-01-18 11:51:16 -0800532 const std::optional<std::string> associatedDisplayUniqueId =
533 getDeviceContext().getAssociatedDisplayUniqueId();
534 if (associatedDisplayUniqueId) {
535 return getDeviceContext().getAssociatedViewport();
536 }
537
Michael Wright227c5542020-07-02 18:30:52 +0100538 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800539 std::optional<DisplayViewport> viewport =
540 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
541 if (viewport) {
542 return viewport;
543 } else {
544 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
545 mConfig.defaultPointerDisplayId);
546 }
547 }
548
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700549 // Check if uniqueDisplayId is specified in idc file.
550 if (!mParameters.uniqueDisplayId.empty()) {
551 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
552 }
553
554 ViewportType viewportTypeToUse;
555 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100556 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700557 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100558 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700559 }
560
561 std::optional<DisplayViewport> viewport =
562 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100563 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700564 ALOGW("Input device %s should be associated with external display, "
565 "fallback to internal one for the external viewport is not found.",
566 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100567 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700568 }
569
570 return viewport;
571 }
572
573 // No associated display, return a non-display viewport.
574 DisplayViewport newViewport;
575 // Raw width and height in the natural orientation.
576 int32_t rawWidth = mRawPointerAxes.getRawWidth();
577 int32_t rawHeight = mRawPointerAxes.getRawHeight();
578 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
579 return std::make_optional(newViewport);
580}
581
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800582int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
583 if (resolution < 0) {
584 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
585 getDeviceName().c_str());
586 return 0;
587 }
588 return resolution;
589}
590
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800591void TouchInputMapper::initializeSizeRanges() {
592 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
593 mSizeScale = 0.0f;
594 return;
595 }
596
597 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000598 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800599
600 // Size factors.
601 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
602 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
603 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
604 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
605 } else {
606 mSizeScale = 0.0f;
607 }
608
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700609 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
610 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
611 .source = mSource,
612 .min = 0,
613 .max = diagonalSize,
614 .flat = 0,
615 .fuzz = 0,
616 .resolution = 0,
617 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800618
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800619 if (mRawPointerAxes.touchMajor.valid) {
620 mRawPointerAxes.touchMajor.resolution =
621 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700622 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800623 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800624
625 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700626 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800627 if (mRawPointerAxes.touchMinor.valid) {
628 mRawPointerAxes.touchMinor.resolution =
629 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700630 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800631 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800632
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700633 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
634 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
635 .source = mSource,
636 .min = 0,
637 .max = diagonalSize,
638 .flat = 0,
639 .fuzz = 0,
640 .resolution = 0,
641 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800642 if (mRawPointerAxes.toolMajor.valid) {
643 mRawPointerAxes.toolMajor.resolution =
644 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700645 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800646 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800647
648 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700649 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800650 if (mRawPointerAxes.toolMinor.valid) {
651 mRawPointerAxes.toolMinor.resolution =
652 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700653 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800654 }
655
656 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700657 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
658 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
659 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
660 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800661 } else {
662 // Support for other calibrations can be added here.
663 ALOGW("%s calibration is not supported for size ranges at the moment. "
664 "Using raw resolution instead",
665 ftl::enum_string(mCalibration.sizeCalibration).c_str());
666 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800667
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700668 mOrientedRanges.size = InputDeviceInfo::MotionRange{
669 .axis = AMOTION_EVENT_AXIS_SIZE,
670 .source = mSource,
671 .min = 0,
672 .max = 1.0,
673 .flat = 0,
674 .fuzz = 0,
675 .resolution = 0,
676 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800677}
678
679void TouchInputMapper::initializeOrientedRanges() {
680 // Configure X and Y factors.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000681 const float orientedScaleX = mRawToDisplay.getScaleX();
682 const float orientedScaleY = mRawToDisplay.getScaleY();
683 mOrientedXPrecision = 1.0f / orientedScaleX;
684 mOrientedYPrecision = 1.0f / orientedScaleY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800685
686 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
687 mOrientedRanges.x.source = mSource;
688 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
689 mOrientedRanges.y.source = mSource;
690
691 // Scale factor for terms that are not oriented in a particular axis.
692 // If the pixels are square then xScale == yScale otherwise we fake it
693 // by choosing an average.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000694 mGeometricScale = avg(orientedScaleX, orientedScaleY);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800695
696 initializeSizeRanges();
697
698 // Pressure factors.
699 mPressureScale = 0;
700 float pressureMax = 1.0;
701 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
702 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700703 if (mCalibration.pressureScale) {
704 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800705 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
706 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
707 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
708 }
709 }
710
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700711 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
712 .axis = AMOTION_EVENT_AXIS_PRESSURE,
713 .source = mSource,
714 .min = 0,
715 .max = pressureMax,
716 .flat = 0,
717 .fuzz = 0,
718 .resolution = 0,
719 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800720
721 // Tilt
722 mTiltXCenter = 0;
723 mTiltXScale = 0;
724 mTiltYCenter = 0;
725 mTiltYScale = 0;
726 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
727 if (mHaveTilt) {
728 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
729 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
730 mTiltXScale = M_PI / 180;
731 mTiltYScale = M_PI / 180;
732
733 if (mRawPointerAxes.tiltX.resolution) {
734 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
735 }
736 if (mRawPointerAxes.tiltY.resolution) {
737 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
738 }
739
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700740 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
741 .axis = AMOTION_EVENT_AXIS_TILT,
742 .source = mSource,
743 .min = 0,
744 .max = M_PI_2,
745 .flat = 0,
746 .fuzz = 0,
747 .resolution = 0,
748 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800749 }
750
751 // Orientation
752 mOrientationScale = 0;
753 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700754 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
755 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
756 .source = mSource,
757 .min = -M_PI,
758 .max = M_PI,
759 .flat = 0,
760 .fuzz = 0,
761 .resolution = 0,
762 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800763
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800764 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
765 if (mCalibration.orientationCalibration ==
766 Calibration::OrientationCalibration::INTERPOLATED) {
767 if (mRawPointerAxes.orientation.valid) {
768 if (mRawPointerAxes.orientation.maxValue > 0) {
769 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
770 } else if (mRawPointerAxes.orientation.minValue < 0) {
771 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
772 } else {
773 mOrientationScale = 0;
774 }
775 }
776 }
777
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700778 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
779 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
780 .source = mSource,
781 .min = -M_PI_2,
782 .max = M_PI_2,
783 .flat = 0,
784 .fuzz = 0,
785 .resolution = 0,
786 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800787 }
788
789 // Distance
790 mDistanceScale = 0;
791 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
792 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700793 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800794 }
795
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700796 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800797
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700798 .axis = AMOTION_EVENT_AXIS_DISTANCE,
799 .source = mSource,
800 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
801 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
802 .flat = 0,
803 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
804 .resolution = 0,
805 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800806 }
807
808 // Compute oriented precision, scales and ranges.
809 // Note that the maximum value reported is an inclusive maximum value so it is one
810 // unit less than the total width or height of the display.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000811 // TODO(b/20508709): Calculate the oriented ranges using the input device's raw frame.
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800812 switch (mInputDeviceOrientation) {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000813 case ui::ROTATION_90:
814 case ui::ROTATION_270:
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800815 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000816 mOrientedRanges.x.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800817 mOrientedRanges.x.flat = 0;
818 mOrientedRanges.x.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000819 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mRawToDisplay.getScaleY();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800820
821 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000822 mOrientedRanges.y.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800823 mOrientedRanges.y.flat = 0;
824 mOrientedRanges.y.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000825 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mRawToDisplay.getScaleX();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800826 break;
827
828 default:
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800829 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000830 mOrientedRanges.x.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800831 mOrientedRanges.x.flat = 0;
832 mOrientedRanges.x.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000833 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mRawToDisplay.getScaleX();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800834
835 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000836 mOrientedRanges.y.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800837 mOrientedRanges.y.flat = 0;
838 mOrientedRanges.y.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000839 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mRawToDisplay.getScaleY();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800840 break;
841 }
842}
843
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000844void TouchInputMapper::computeInputTransforms() {
Prabir Pradhan3e798762022-12-02 21:02:11 +0000845 constexpr auto isRotated = [](const ui::Transform::RotationFlags& rotation) {
846 return rotation == ui::Transform::ROT_90 || rotation == ui::Transform::ROT_270;
847 };
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000848
Prabir Pradhan3e798762022-12-02 21:02:11 +0000849 // See notes about input coordinates in the inputflinger docs:
850 // //frameworks/native/services/inputflinger/docs/input_coordinates.md
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000851
852 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
Prabir Pradhan3e798762022-12-02 21:02:11 +0000853 ui::Transform undoOffsetInRaw;
854 undoOffsetInRaw.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000855
Prabir Pradhan3e798762022-12-02 21:02:11 +0000856 // Step 2: Rotate the raw coordinates to account for input device orientation. The coordinates
857 // will now be in the same orientation as the display in ROTATION_0.
858 // Note: Negating an ui::Rotation value will give its inverse rotation.
859 const auto inputDeviceOrientation = ui::Transform::toRotationFlags(-mParameters.orientation);
860 const ui::Size orientedRawSize = isRotated(inputDeviceOrientation)
861 ? ui::Size{mRawPointerAxes.getRawHeight(), mRawPointerAxes.getRawWidth()}
862 : ui::Size{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
863 // When rotating raw values, account for the extra unit added when calculating the raw range.
864 const auto orientInRaw = ui::Transform(inputDeviceOrientation, orientedRawSize.width - 1,
865 orientedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000866
Prabir Pradhan3e798762022-12-02 21:02:11 +0000867 // Step 3: Rotate the raw coordinates to account for the display rotation. The coordinates will
868 // now be in the same orientation as the rotated display. There is no need to rotate the
869 // coordinates to the display rotation if the device is not orientation-aware.
870 const auto viewportRotation = ui::Transform::toRotationFlags(-mViewport.orientation);
871 const auto rotatedRawSize = mParameters.orientationAware && isRotated(viewportRotation)
872 ? ui::Size{orientedRawSize.height, orientedRawSize.width}
873 : orientedRawSize;
874 // When rotating raw values, account for the extra unit added when calculating the raw range.
875 const auto rotateInRaw = mParameters.orientationAware
876 ? ui::Transform(viewportRotation, rotatedRawSize.width - 1, rotatedRawSize.height - 1)
877 : ui::Transform();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000878
Prabir Pradhan3e798762022-12-02 21:02:11 +0000879 // Step 4: Scale the raw coordinates to the display space.
880 // - Here, we assume that the raw surface of the touch device maps perfectly to the surface
881 // of the display panel. This is usually true for touchscreens.
882 // - From this point onward, we are no longer in the discrete space of the raw coordinates but
883 // are in the continuous space of the logical display.
884 ui::Transform scaleRawToDisplay;
885 const float xScale = static_cast<float>(mViewport.deviceWidth) / rotatedRawSize.width;
886 const float yScale = static_cast<float>(mViewport.deviceHeight) / rotatedRawSize.height;
887 scaleRawToDisplay.set(xScale, 0, 0, yScale);
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000888
Prabir Pradhan3e798762022-12-02 21:02:11 +0000889 // Step 5: Undo the display rotation to bring us back to the un-rotated display coordinate space
890 // that InputReader uses.
891 const auto undoRotateInDisplay =
892 ui::Transform(viewportRotation, mViewport.deviceWidth, mViewport.deviceHeight)
893 .inverse();
894
895 // Now put it all together!
896 mRawToRotatedDisplay = (scaleRawToDisplay * (rotateInRaw * (orientInRaw * undoOffsetInRaw)));
897 mRawToDisplay = (undoRotateInDisplay * mRawToRotatedDisplay);
898 mRawRotation = ui::Transform{mRawToDisplay.getOrientation()};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000899}
900
Prabir Pradhan1728b212021-10-19 16:00:03 -0700901void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000902 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700903
904 resolveExternalStylusPresence();
905
906 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100907 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000908 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700909 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100910 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700911 if (hasStylus()) {
912 mSource |= AINPUT_SOURCE_STYLUS;
913 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800914 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700915 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100916 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700917 if (hasStylus()) {
918 mSource |= AINPUT_SOURCE_STYLUS;
919 }
920 if (hasExternalStylus()) {
921 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
922 }
Michael Wright227c5542020-07-02 18:30:52 +0100923 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700924 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100925 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700926 } else {
927 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100928 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700929 }
930
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000931 const std::optional<DisplayViewport> newViewportOpt = findViewport();
932
933 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700934 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
935 ALOGW("Touch device '%s' did not report support for X or Y axis! "
936 "The device will be inoperable.",
937 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100938 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000939 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700940 ALOGI("Touch device '%s' could not query the properties of its associated "
941 "display. The device will be inoperable until the display size "
942 "becomes available.",
943 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100944 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700945 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000946 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
947 getDeviceName().c_str(), getDeviceId());
948 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000949 }
950
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700951 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000952 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000953 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
954 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
955 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
956 const float rawMeanResolution =
957 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700958
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000959 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
960 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700961 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700962 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000963 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
964 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
965 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700966
Michael Wright227c5542020-07-02 18:30:52 +0100967 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000968 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700969
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000970 mDisplayBounds = getNaturalDisplaySize(mViewport);
971 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
972 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700973
Prabir Pradhan3e798762022-12-02 21:02:11 +0000974 // TODO(b/257118693): Remove the dependence on the old orientation/rotation logic that
975 // uses mInputDeviceOrientation. The new logic uses the transforms calculated in
976 // computeInputTransforms().
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000977 // InputReader works in the un-rotated display coordinate space, so we don't need to do
978 // anything if the device is already orientation-aware. If the device is not
979 // orientation-aware, then we need to apply the inverse rotation of the display so that
980 // when the display rotation is applied later as a part of the per-window transform, we
981 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700982 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +0000983 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000984 : getInverseRotation(mViewport.orientation);
985 // For orientation-aware devices that work in the un-rotated coordinate space, the
986 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000987 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000988 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700989
990 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +0000991 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000992 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700993 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000994 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000995 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +0000996 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000997 mRawToDisplay.reset();
998 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000999 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001000 }
1001 }
1002
1003 // If moving between pointer modes, need to reset some state.
1004 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1005 if (deviceModeChanged) {
1006 mOrientedRanges.clear();
1007 }
1008
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001009 // Create and preserve the pointer controller in the following cases:
1010 const bool isPointerControllerNeeded =
1011 // - when the device is in pointer mode, to show the mouse cursor;
1012 (mDeviceMode == DeviceMode::POINTER) ||
1013 // - when pointer capture is enabled, to preserve the mouse cursor position;
1014 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
1015 mConfig.pointerCaptureRequest.enable) ||
1016 // - when we should be showing touches;
1017 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
1018 // - when we should be showing a pointer icon for direct styluses.
1019 (mDeviceMode == DeviceMode::DIRECT && mConfig.stylusPointerIconEnabled && hasStylus());
1020 if (isPointerControllerNeeded) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001021 if (mPointerController == nullptr) {
1022 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001023 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001024 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001025 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1026 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001027 } else {
lilinnandef700b2022-06-17 19:32:01 +08001028 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1029 !mConfig.showTouches) {
1030 mPointerController->clearSpots();
1031 }
Michael Wright17db18e2020-06-26 20:51:44 +01001032 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001033 }
1034
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001035 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001036 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001037 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001038 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001039 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001040
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001041 configureVirtualKeys();
1042
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001043 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001044
1045 // Location
1046 updateAffineTransformation();
1047
Michael Wright227c5542020-07-02 18:30:52 +01001048 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001049 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001050 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1051 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001052
1053 // Scale movements such that one whole swipe of the touch pad covers a
1054 // given area relative to the diagonal size of the display when no acceleration
1055 // is applied.
1056 // Assume that the touch pad has a square aspect ratio such that movements in
1057 // X and Y of the same number of raw units cover the same physical distance.
1058 mPointerXMovementScale =
1059 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1060 mPointerYMovementScale = mPointerXMovementScale;
1061
1062 // Scale zooms to cover a smaller range of the display than movements do.
1063 // This value determines the area around the pointer that is affected by freeform
1064 // pointer gestures.
1065 mPointerXZoomScale =
1066 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1067 mPointerYZoomScale = mPointerXZoomScale;
1068
HQ Liue6983c72022-04-19 22:14:56 +00001069 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1070 // axis is non positive value.
1071 const float minFreeformGestureWidth =
1072 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1073
1074 mPointerGestureMaxSwipeWidth =
1075 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1076 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001077 }
1078
1079 // Inform the dispatcher about the changes.
1080 *outResetNeeded = true;
1081 bumpGeneration();
1082 }
1083}
1084
Prabir Pradhan1728b212021-10-19 16:00:03 -07001085void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001086 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001087 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001088 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1089 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001090 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001091}
1092
1093void TouchInputMapper::configureVirtualKeys() {
1094 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001095 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001096
1097 mVirtualKeys.clear();
1098
1099 if (virtualKeyDefinitions.size() == 0) {
1100 return;
1101 }
1102
1103 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1104 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1105 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1106 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1107
1108 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1109 VirtualKey virtualKey;
1110
1111 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1112 int32_t keyCode;
1113 int32_t dummyKeyMetaState;
1114 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001115 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1116 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001117 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1118 continue; // drop the key
1119 }
1120
1121 virtualKey.keyCode = keyCode;
1122 virtualKey.flags = flags;
1123
1124 // convert the key definition's display coordinates into touch coordinates for a hit box
1125 int32_t halfWidth = virtualKeyDefinition.width / 2;
1126 int32_t halfHeight = virtualKeyDefinition.height / 2;
1127
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001128 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1129 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001130 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001131 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1132 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001133 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001134 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1135 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001136 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001137 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1138 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139 touchScreenTop;
1140 mVirtualKeys.push_back(virtualKey);
1141 }
1142}
1143
1144void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1145 if (!mVirtualKeys.empty()) {
1146 dump += INDENT3 "Virtual Keys:\n";
1147
1148 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1149 const VirtualKey& virtualKey = mVirtualKeys[i];
1150 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1151 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1152 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1153 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1154 }
1155 }
1156}
1157
1158void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001159 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001160 Calibration& out = mCalibration;
1161
1162 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001163 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001164 std::string sizeCalibrationString;
1165 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001166 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001167 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001168 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001169 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001173 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001175 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001177 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001178 }
1179 }
1180
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001181 float sizeScale;
1182
1183 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1184 out.sizeScale = sizeScale;
1185 }
1186 float sizeBias;
1187 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1188 out.sizeBias = sizeBias;
1189 }
1190 bool sizeIsSummed;
1191 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1192 out.sizeIsSummed = sizeIsSummed;
1193 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001194
1195 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001196 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001197 std::string pressureCalibrationString;
1198 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001199 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001201 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001202 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001203 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001204 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 } else if (pressureCalibrationString != "default") {
1206 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001207 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001208 }
1209 }
1210
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001211 float pressureScale;
1212 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1213 out.pressureScale = pressureScale;
1214 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001215
1216 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001217 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001218 std::string orientationCalibrationString;
1219 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001220 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001221 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001222 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001223 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001224 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001225 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001226 } else if (orientationCalibrationString != "default") {
1227 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001228 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229 }
1230 }
1231
1232 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001233 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001234 std::string distanceCalibrationString;
1235 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001236 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001237 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001238 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001239 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001240 } else if (distanceCalibrationString != "default") {
1241 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001242 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001243 }
1244 }
1245
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001246 float distanceScale;
1247 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1248 out.distanceScale = distanceScale;
1249 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001250}
1251
1252void TouchInputMapper::resolveCalibration() {
1253 // Size
1254 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001255 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1256 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001257 }
1258 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001259 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001260 }
1261
1262 // Pressure
1263 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001264 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1265 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001266 }
1267 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001268 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001269 }
1270
1271 // Orientation
1272 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001273 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1274 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001275 }
1276 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001277 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001278 }
1279
1280 // Distance
1281 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001282 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1283 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284 }
1285 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001286 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001288}
1289
1290void TouchInputMapper::dumpCalibration(std::string& dump) {
1291 dump += INDENT3 "Calibration:\n";
1292
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001293 dump += INDENT4 "touch.size.calibration: ";
1294 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001295
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001296 if (mCalibration.sizeScale) {
1297 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 }
1299
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001300 if (mCalibration.sizeBias) {
1301 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001302 }
1303
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001304 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001305 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001306 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 }
1308
1309 // Pressure
1310 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001311 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001312 dump += INDENT4 "touch.pressure.calibration: none\n";
1313 break;
Michael Wright227c5542020-07-02 18:30:52 +01001314 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001315 dump += INDENT4 "touch.pressure.calibration: physical\n";
1316 break;
Michael Wright227c5542020-07-02 18:30:52 +01001317 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001318 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1319 break;
1320 default:
1321 ALOG_ASSERT(false);
1322 }
1323
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001324 if (mCalibration.pressureScale) {
1325 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001326 }
1327
1328 // Orientation
1329 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001330 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 dump += INDENT4 "touch.orientation.calibration: none\n";
1332 break;
Michael Wright227c5542020-07-02 18:30:52 +01001333 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001334 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1335 break;
Michael Wright227c5542020-07-02 18:30:52 +01001336 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001337 dump += INDENT4 "touch.orientation.calibration: vector\n";
1338 break;
1339 default:
1340 ALOG_ASSERT(false);
1341 }
1342
1343 // Distance
1344 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001345 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001346 dump += INDENT4 "touch.distance.calibration: none\n";
1347 break;
Michael Wright227c5542020-07-02 18:30:52 +01001348 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001349 dump += INDENT4 "touch.distance.calibration: scaled\n";
1350 break;
1351 default:
1352 ALOG_ASSERT(false);
1353 }
1354
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001355 if (mCalibration.distanceScale) {
1356 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001357 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001358}
1359
1360void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1361 dump += INDENT3 "Affine Transformation:\n";
1362
1363 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1364 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1365 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1366 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1367 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1368 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1369}
1370
1371void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001372 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001373 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001374}
1375
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001376std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001377 std::list<NotifyArgs> out = cancelTouch(when, when);
1378 updateTouchSpots();
1379
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001380 mCursorButtonAccumulator.reset(getDeviceContext());
1381 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001382 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001383
1384 mPointerVelocityControl.reset();
1385 mWheelXVelocityControl.reset();
1386 mWheelYVelocityControl.reset();
1387
1388 mRawStatesPending.clear();
1389 mCurrentRawState.clear();
1390 mCurrentCookedState.clear();
1391 mLastRawState.clear();
1392 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001393 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001394 mSentHoverEnter = false;
1395 mHavePointerIds = false;
1396 mCurrentMotionAborted = false;
1397 mDownTime = 0;
1398
1399 mCurrentVirtualKey.down = false;
1400
1401 mPointerGesture.reset();
1402 mPointerSimple.reset();
1403 resetExternalStylus();
1404
1405 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001406 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001407 mPointerController->clearSpots();
1408 }
1409
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001410 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001411}
1412
1413void TouchInputMapper::resetExternalStylus() {
1414 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001415 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001416 mExternalStylusFusionTimeout = LLONG_MAX;
1417 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001418 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001419}
1420
1421void TouchInputMapper::clearStylusDataPendingFlags() {
1422 mExternalStylusDataPending = false;
1423 mExternalStylusFusionTimeout = LLONG_MAX;
1424}
1425
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001426std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001427 mCursorButtonAccumulator.process(rawEvent);
1428 mCursorScrollAccumulator.process(rawEvent);
1429 mTouchButtonAccumulator.process(rawEvent);
1430
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001431 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001432 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001433 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001434 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001435 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001436}
1437
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001438std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1439 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001440 if (mDeviceMode == DeviceMode::DISABLED) {
1441 // Only save the last pending state when the device is disabled.
1442 mRawStatesPending.clear();
1443 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001444 // Push a new state.
1445 mRawStatesPending.emplace_back();
1446
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001447 RawState& next = mRawStatesPending.back();
1448 next.clear();
1449 next.when = when;
1450 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001451
1452 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001453 next.buttonState = filterButtonState(mConfig,
1454 mTouchButtonAccumulator.getButtonState() |
1455 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001456
1457 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001458 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1459 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001460 mCursorScrollAccumulator.finishSync();
1461
1462 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001463 syncTouch(when, &next);
1464
1465 // The last RawState is the actually second to last, since we just added a new state
1466 const RawState& last =
1467 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001468
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001469 std::tie(next.when, next.readTime) =
1470 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1471 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001472
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001473 // Assign pointer ids.
1474 if (!mHavePointerIds) {
1475 assignPointerIds(last, next);
1476 }
1477
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001478 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001479 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1480 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1481 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1482 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1483 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1484 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001485
Arthur Hung9ad18942021-06-19 02:04:46 +00001486 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1487 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1488 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1489 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1490 next.rawPointerData.hoveringIdBits.value);
1491 }
1492
Harry Cutts33476232023-01-30 19:57:29 +00001493 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001494 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001495}
1496
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001497std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1498 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001499 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001500 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001501 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001502 }
1503
1504 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1505 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1506 // touching the current state will only observe the events that have been dispatched to the
1507 // rest of the pipeline.
1508 const size_t N = mRawStatesPending.size();
1509 size_t count;
1510 for (count = 0; count < N; count++) {
1511 const RawState& next = mRawStatesPending[count];
1512
1513 // A failure to assign the stylus id means that we're waiting on stylus data
1514 // and so should defer the rest of the pipeline.
1515 if (assignExternalStylusId(next, timeout)) {
1516 break;
1517 }
1518
1519 // All ready to go.
1520 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001521 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001522 if (mCurrentRawState.when < mLastRawState.when) {
1523 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001524 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001525 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001526 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001527 }
1528 if (count != 0) {
1529 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1530 }
1531
1532 if (mExternalStylusDataPending) {
1533 if (timeout) {
1534 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1535 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001536 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001537 ALOGD_IF(DEBUG_STYLUS_FUSION,
1538 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001539 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001540 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001541 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1542 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1543 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1544 }
1545 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001546 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001547}
1548
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001549std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1550 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001551 // Always start with a clean state.
1552 mCurrentCookedState.clear();
1553
1554 // Apply stylus buttons to current raw state.
1555 applyExternalStylusButtonState(when);
1556
1557 // Handle policy on initial down or hover events.
1558 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1559 mCurrentRawState.rawPointerData.pointerCount != 0;
1560
1561 uint32_t policyFlags = 0;
1562 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1563 if (initialDown || buttonsPressed) {
1564 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001565 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001566 getContext()->fadePointer();
1567 }
1568
1569 if (mParameters.wake) {
1570 policyFlags |= POLICY_FLAG_WAKE;
1571 }
1572 }
1573
1574 // Consume raw off-screen touches before cooking pointer data.
1575 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001576 bool consumed;
1577 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1578 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001579 mCurrentRawState.rawPointerData.clear();
1580 }
1581
1582 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1583 // with cooked pointer data that has the same ids and indices as the raw data.
1584 // The following code can use either the raw or cooked data, as needed.
1585 cookPointerData();
1586
1587 // Apply stylus pressure to current cooked state.
1588 applyExternalStylusTouchState(when);
1589
1590 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001591 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1592 mSource, mViewport.displayId, policyFlags,
1593 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001594
1595 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001596 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001597 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1598 uint32_t id = idBits.clearFirstMarkedBit();
1599 const RawPointerData::Pointer& pointer =
1600 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001601 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001602 mCurrentCookedState.stylusIdBits.markBit(id);
1603 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1604 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1605 mCurrentCookedState.fingerIdBits.markBit(id);
1606 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1607 mCurrentCookedState.mouseIdBits.markBit(id);
1608 }
1609 }
1610 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1611 uint32_t id = idBits.clearFirstMarkedBit();
1612 const RawPointerData::Pointer& pointer =
1613 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001614 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001615 mCurrentCookedState.stylusIdBits.markBit(id);
1616 }
1617 }
1618
1619 // Stylus takes precedence over all tools, then mouse, then finger.
1620 PointerUsage pointerUsage = mPointerUsage;
1621 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1622 mCurrentCookedState.mouseIdBits.clear();
1623 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001624 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001625 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1626 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001627 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001628 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1629 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001630 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001631 }
1632
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001633 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001634 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001635 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001636 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001637 out += dispatchButtonRelease(when, readTime, policyFlags);
1638 out += dispatchHoverExit(when, readTime, policyFlags);
1639 out += dispatchTouches(when, readTime, policyFlags);
1640 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1641 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001642 }
1643
1644 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1645 mCurrentMotionAborted = false;
1646 }
1647 }
1648
1649 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001650 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1651 mSource, mViewport.displayId, policyFlags,
1652 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001653
1654 // Clear some transient state.
1655 mCurrentRawState.rawVScroll = 0;
1656 mCurrentRawState.rawHScroll = 0;
1657
1658 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001659 mLastRawState = mCurrentRawState;
1660 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001661 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001662}
1663
Garfield Tanc734e4f2021-01-15 20:01:39 -08001664void TouchInputMapper::updateTouchSpots() {
1665 if (!mConfig.showTouches || mPointerController == nullptr) {
1666 return;
1667 }
1668
1669 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1670 // clear touch spots.
1671 if (mDeviceMode != DeviceMode::DIRECT &&
1672 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1673 return;
1674 }
1675
1676 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1677 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1678
1679 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001680 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1681 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhanb3ce4532023-03-03 22:20:54 +00001682 mCurrentCookedState.cookedPointerData.touchingIdBits |
1683 mCurrentCookedState.cookedPointerData.hoveringIdBits,
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001684 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001685}
1686
1687bool TouchInputMapper::isTouchScreen() {
1688 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1689 mParameters.hasAssociatedDisplay;
1690}
1691
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001692void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001693 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1694 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001695 const int32_t pressedButtons =
1696 filterButtonState(mConfig,
1697 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001698 const int32_t releasedButtons =
1699 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1700
1701 mCurrentRawState.buttonState |= pressedButtons;
1702 mCurrentRawState.buttonState &= ~releasedButtons;
1703
1704 mExternalStylusButtonsApplied |= pressedButtons;
1705 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001706 }
1707}
1708
1709void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1710 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1711 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001712 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1713 return;
1714 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001715
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001716 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1717 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1718 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1719 : 0.f;
1720 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1721 pressure = *mExternalStylusState.pressure;
1722 }
1723 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1724 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001725
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001726 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001727 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001728 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001729 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001730 }
1731}
1732
1733bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001734 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001735 return false;
1736 }
1737
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001738 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001739 if (mFusedStylusPointerId &&
1740 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001741 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001742 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001743 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001744 }
1745
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001746 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1747 state.rawPointerData.pointerCount != 0;
1748 if (!initialDown) {
1749 return false;
1750 }
1751
1752 if (!mExternalStylusState.pressure) {
1753 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1754 return false;
1755 }
1756
1757 if (*mExternalStylusState.pressure != 0.0f) {
1758 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1759 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1760 return false;
1761 }
1762
1763 if (timeout) {
1764 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1765 mFusedStylusPointerId.reset();
1766 mExternalStylusFusionTimeout = LLONG_MAX;
1767 return false;
1768 }
1769
1770 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1771 // being processed until we either get pressure data or timeout.
1772 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1773 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1774 }
1775 ALOGD_IF(DEBUG_STYLUS_FUSION,
1776 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1777 mExternalStylusFusionTimeout);
1778 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1779 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001780}
1781
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001782std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1783 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001784 if (mDeviceMode == DeviceMode::POINTER) {
1785 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001786 // Since this is a synthetic event, we can consider its latency to be zero
1787 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001788 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001789 }
Michael Wright227c5542020-07-02 18:30:52 +01001790 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001791 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001792 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001793 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1794 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1795 }
1796 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001797 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001798}
1799
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001800std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1801 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001802 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001803 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001804 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001805 // The following three cases are handled here:
1806 // - We're in the middle of a fused stream of data;
1807 // - We're waiting on external stylus data before dispatching the initial down; or
1808 // - Only the button state, which is not reported through a specific pointer, has changed.
1809 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001810 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001811 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001812 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001813 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001814}
1815
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001816std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1817 uint32_t policyFlags, bool& outConsumed) {
1818 outConsumed = false;
1819 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001820 // Check for release of a virtual key.
1821 if (mCurrentVirtualKey.down) {
1822 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1823 // Pointer went up while virtual key was down.
1824 mCurrentVirtualKey.down = false;
1825 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001826 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1827 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1828 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001829 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1830 AKEY_EVENT_FLAG_FROM_SYSTEM |
1831 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001832 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001833 outConsumed = true;
1834 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001835 }
1836
1837 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1838 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1839 const RawPointerData::Pointer& pointer =
1840 mCurrentRawState.rawPointerData.pointerForId(id);
1841 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1842 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1843 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001844 outConsumed = true;
1845 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001846 }
1847 }
1848
1849 // Pointer left virtual key area or another pointer also went down.
1850 // Send key cancellation but do not consume the touch yet.
1851 // This is useful when the user swipes through from the virtual key area
1852 // into the main display surface.
1853 mCurrentVirtualKey.down = false;
1854 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001855 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1856 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001857 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1858 AKEY_EVENT_FLAG_FROM_SYSTEM |
1859 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1860 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001861 }
1862 }
1863
1864 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1865 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1866 // Pointer just went down. Check for virtual key press or off-screen touches.
1867 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1868 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001869 // Skip checking whether the pointer is inside the physical frame if the device is in
1870 // unscaled mode.
1871 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1872 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001873 // If exactly one pointer went down, check for virtual key hit.
1874 // Otherwise we will drop the entire stroke.
1875 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1876 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1877 if (virtualKey) {
1878 mCurrentVirtualKey.down = true;
1879 mCurrentVirtualKey.downTime = when;
1880 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1881 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1882 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001883 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1884 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001885
1886 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001887 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1888 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1889 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001890 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1891 AKEY_EVENT_ACTION_DOWN,
1892 AKEY_EVENT_FLAG_FROM_SYSTEM |
1893 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001894 }
1895 }
1896 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001897 outConsumed = true;
1898 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001899 }
1900 }
1901
1902 // Disable all virtual key touches that happen within a short time interval of the
1903 // most recent touch within the screen area. The idea is to filter out stray
1904 // virtual key presses when interacting with the touch screen.
1905 //
1906 // Problems we're trying to solve:
1907 //
1908 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1909 // virtual key area that is implemented by a separate touch panel and accidentally
1910 // triggers a virtual key.
1911 //
1912 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1913 // area and accidentally triggers a virtual key. This often happens when virtual keys
1914 // are layed out below the screen near to where the on screen keyboard's space bar
1915 // is displayed.
1916 if (mConfig.virtualKeyQuietTime > 0 &&
1917 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001918 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001919 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001920 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001921}
1922
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001923NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1924 uint32_t policyFlags, int32_t keyEventAction,
1925 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001926 int32_t keyCode = mCurrentVirtualKey.keyCode;
1927 int32_t scanCode = mCurrentVirtualKey.scanCode;
1928 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001929 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001930 policyFlags |= POLICY_FLAG_VIRTUAL;
1931
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001932 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1933 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1934 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001935}
1936
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001937std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1938 uint32_t policyFlags) {
1939 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001940 if (mCurrentMotionAborted) {
1941 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001942 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001943 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001944 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1945 if (!currentIdBits.isEmpty()) {
1946 int32_t metaState = getContext()->getGlobalMetaState();
1947 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001948 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001949 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1950 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001951 mCurrentCookedState.cookedPointerData.pointerProperties,
1952 mCurrentCookedState.cookedPointerData.pointerCoords,
1953 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1954 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1955 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001956 mCurrentMotionAborted = true;
1957 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001958 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001959}
1960
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001961// Updates pointer coords and properties for pointers with specified ids that have moved.
1962// Returns true if any of them changed.
1963static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1964 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1965 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1966 BitSet32 idBits) {
1967 bool changed = false;
1968 while (!idBits.isEmpty()) {
1969 uint32_t id = idBits.clearFirstMarkedBit();
1970 uint32_t inIndex = inIdToIndex[id];
1971 uint32_t outIndex = outIdToIndex[id];
1972
1973 const PointerProperties& curInProperties = inProperties[inIndex];
1974 const PointerCoords& curInCoords = inCoords[inIndex];
1975 PointerProperties& curOutProperties = outProperties[outIndex];
1976 PointerCoords& curOutCoords = outCoords[outIndex];
1977
1978 if (curInProperties != curOutProperties) {
1979 curOutProperties.copyFrom(curInProperties);
1980 changed = true;
1981 }
1982
1983 if (curInCoords != curOutCoords) {
1984 curOutCoords.copyFrom(curInCoords);
1985 changed = true;
1986 }
1987 }
1988 return changed;
1989}
1990
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001991std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1992 uint32_t policyFlags) {
1993 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001994 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1995 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1996 int32_t metaState = getContext()->getGlobalMetaState();
1997 int32_t buttonState = mCurrentCookedState.buttonState;
1998
1999 if (currentIdBits == lastIdBits) {
2000 if (!currentIdBits.isEmpty()) {
2001 // No pointer id changes so this is a move event.
2002 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002003 out.push_back(
2004 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
2005 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2006 mCurrentCookedState.cookedPointerData.pointerProperties,
2007 mCurrentCookedState.cookedPointerData.pointerCoords,
2008 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
2009 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2010 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002011 }
2012 } else {
2013 // There may be pointers going up and pointers going down and pointers moving
2014 // all at the same time.
2015 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
2016 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
2017 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2018 BitSet32 dispatchedIdBits(lastIdBits.value);
2019
2020 // Update last coordinates of pointers that have moved so that we observe the new
2021 // pointer positions at the same time as other pointers that have just gone up.
2022 bool moveNeeded =
2023 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2024 mCurrentCookedState.cookedPointerData.pointerCoords,
2025 mCurrentCookedState.cookedPointerData.idToIndex,
2026 mLastCookedState.cookedPointerData.pointerProperties,
2027 mLastCookedState.cookedPointerData.pointerCoords,
2028 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2029 if (buttonState != mLastCookedState.buttonState) {
2030 moveNeeded = true;
2031 }
2032
2033 // Dispatch pointer up events.
2034 while (!upIdBits.isEmpty()) {
2035 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002036 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002037 if (isCanceled) {
2038 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2039 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002040 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2041 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2042 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2043 buttonState, 0,
2044 mLastCookedState.cookedPointerData.pointerProperties,
2045 mLastCookedState.cookedPointerData.pointerCoords,
2046 mLastCookedState.cookedPointerData.idToIndex,
2047 dispatchedIdBits, upId, mOrientedXPrecision,
2048 mOrientedYPrecision, mDownTime,
2049 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002050 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002051 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002052 }
2053
2054 // Dispatch move events if any of the remaining pointers moved from their old locations.
2055 // Although applications receive new locations as part of individual pointer up
2056 // events, they do not generally handle them except when presented in a move event.
2057 if (moveNeeded && !moveIdBits.isEmpty()) {
2058 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002059 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2060 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2061 mCurrentCookedState.cookedPointerData.pointerProperties,
2062 mCurrentCookedState.cookedPointerData.pointerCoords,
2063 mCurrentCookedState.cookedPointerData.idToIndex,
2064 dispatchedIdBits, -1, mOrientedXPrecision,
2065 mOrientedYPrecision, mDownTime,
2066 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002067 }
2068
2069 // Dispatch pointer down events using the new pointer locations.
2070 while (!downIdBits.isEmpty()) {
2071 uint32_t downId = downIdBits.clearFirstMarkedBit();
2072 dispatchedIdBits.markBit(downId);
2073
2074 if (dispatchedIdBits.count() == 1) {
2075 // First pointer is going down. Set down time.
2076 mDownTime = when;
2077 }
2078
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002079 out.push_back(
2080 dispatchMotion(when, readTime, policyFlags, mSource,
2081 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2082 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2083 mCurrentCookedState.cookedPointerData.pointerCoords,
2084 mCurrentCookedState.cookedPointerData.idToIndex,
2085 dispatchedIdBits, downId, mOrientedXPrecision,
2086 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002087 }
2088 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002089 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002090}
2091
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002092std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2093 uint32_t policyFlags) {
2094 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002095 if (mSentHoverEnter &&
2096 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2097 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2098 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002099 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2100 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2101 mLastCookedState.buttonState, 0,
2102 mLastCookedState.cookedPointerData.pointerProperties,
2103 mLastCookedState.cookedPointerData.pointerCoords,
2104 mLastCookedState.cookedPointerData.idToIndex,
2105 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2106 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2107 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002108 mSentHoverEnter = false;
2109 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002110 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002111}
2112
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002113std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2114 uint32_t policyFlags) {
2115 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002116 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2117 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2118 int32_t metaState = getContext()->getGlobalMetaState();
2119 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002120 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2121 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2122 mCurrentRawState.buttonState, 0,
2123 mCurrentCookedState.cookedPointerData.pointerProperties,
2124 mCurrentCookedState.cookedPointerData.pointerCoords,
2125 mCurrentCookedState.cookedPointerData.idToIndex,
2126 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2127 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2128 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002129 mSentHoverEnter = true;
2130 }
2131
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002132 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2133 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2134 mCurrentRawState.buttonState, 0,
2135 mCurrentCookedState.cookedPointerData.pointerProperties,
2136 mCurrentCookedState.cookedPointerData.pointerCoords,
2137 mCurrentCookedState.cookedPointerData.idToIndex,
2138 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2139 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2140 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002141 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002142 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002143}
2144
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002145std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2146 uint32_t policyFlags) {
2147 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002148 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2149 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2150 const int32_t metaState = getContext()->getGlobalMetaState();
2151 int32_t buttonState = mLastCookedState.buttonState;
2152 while (!releasedButtons.isEmpty()) {
2153 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2154 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002155 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2156 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2157 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002158 mLastCookedState.cookedPointerData.pointerProperties,
2159 mLastCookedState.cookedPointerData.pointerCoords,
2160 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002161 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2162 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002163 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002164 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002165}
2166
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002167std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2168 uint32_t policyFlags) {
2169 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002170 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2171 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2172 const int32_t metaState = getContext()->getGlobalMetaState();
2173 int32_t buttonState = mLastCookedState.buttonState;
2174 while (!pressedButtons.isEmpty()) {
2175 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2176 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002177 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2178 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2179 buttonState, 0,
2180 mCurrentCookedState.cookedPointerData.pointerProperties,
2181 mCurrentCookedState.cookedPointerData.pointerCoords,
2182 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2183 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2184 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002185 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002186 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002187}
2188
LiZhihong758eb562022-11-03 15:28:29 +08002189std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2190 uint32_t policyFlags,
2191 BitSet32 idBits,
2192 nsecs_t readTime) {
2193 std::list<NotifyArgs> out;
2194 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2195 const int32_t metaState = getContext()->getGlobalMetaState();
2196 int32_t buttonState = mLastCookedState.buttonState;
2197
2198 while (!releasedButtons.isEmpty()) {
2199 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2200 buttonState &= ~actionButton;
2201 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2202 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2203 metaState, buttonState, 0,
2204 mPointerGesture.lastGestureProperties,
2205 mPointerGesture.lastGestureCoords,
2206 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2207 mOrientedXPrecision, mOrientedYPrecision,
2208 mPointerGesture.downTime, MotionClassification::NONE));
2209 }
2210 return out;
2211}
2212
2213std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2214 uint32_t policyFlags,
2215 BitSet32 idBits,
2216 nsecs_t readTime) {
2217 std::list<NotifyArgs> out;
2218 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2219 const int32_t metaState = getContext()->getGlobalMetaState();
2220 int32_t buttonState = mLastCookedState.buttonState;
2221
2222 while (!pressedButtons.isEmpty()) {
2223 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2224 buttonState |= actionButton;
2225 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2226 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2227 buttonState, 0, mPointerGesture.currentGestureProperties,
2228 mPointerGesture.currentGestureCoords,
2229 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2230 mOrientedXPrecision, mOrientedYPrecision,
2231 mPointerGesture.downTime, MotionClassification::NONE));
2232 }
2233 return out;
2234}
2235
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002236const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2237 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2238 return cookedPointerData.touchingIdBits;
2239 }
2240 return cookedPointerData.hoveringIdBits;
2241}
2242
2243void TouchInputMapper::cookPointerData() {
2244 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2245
2246 mCurrentCookedState.cookedPointerData.clear();
2247 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2248 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2249 mCurrentRawState.rawPointerData.hoveringIdBits;
2250 mCurrentCookedState.cookedPointerData.touchingIdBits =
2251 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002252 mCurrentCookedState.cookedPointerData.canceledIdBits =
2253 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002254
2255 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2256 mCurrentCookedState.buttonState = 0;
2257 } else {
2258 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2259 }
2260
2261 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002262 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002263 for (uint32_t i = 0; i < currentPointerCount; i++) {
2264 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2265
2266 // Size
2267 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2268 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002269 case Calibration::SizeCalibration::GEOMETRIC:
2270 case Calibration::SizeCalibration::DIAMETER:
2271 case Calibration::SizeCalibration::BOX:
2272 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002273 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2274 touchMajor = in.touchMajor;
2275 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2276 toolMajor = in.toolMajor;
2277 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2278 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2279 : in.touchMajor;
2280 } else if (mRawPointerAxes.touchMajor.valid) {
2281 toolMajor = touchMajor = in.touchMajor;
2282 toolMinor = touchMinor =
2283 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2284 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2285 : in.touchMajor;
2286 } else if (mRawPointerAxes.toolMajor.valid) {
2287 touchMajor = toolMajor = in.toolMajor;
2288 touchMinor = toolMinor =
2289 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2290 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2291 : in.toolMajor;
2292 } else {
2293 ALOG_ASSERT(false,
2294 "No touch or tool axes. "
2295 "Size calibration should have been resolved to NONE.");
2296 touchMajor = 0;
2297 touchMinor = 0;
2298 toolMajor = 0;
2299 toolMinor = 0;
2300 size = 0;
2301 }
2302
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002303 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002304 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2305 if (touchingCount > 1) {
2306 touchMajor /= touchingCount;
2307 touchMinor /= touchingCount;
2308 toolMajor /= touchingCount;
2309 toolMinor /= touchingCount;
2310 size /= touchingCount;
2311 }
2312 }
2313
Michael Wright227c5542020-07-02 18:30:52 +01002314 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002315 touchMajor *= mGeometricScale;
2316 touchMinor *= mGeometricScale;
2317 toolMajor *= mGeometricScale;
2318 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002319 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002320 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2321 touchMinor = touchMajor;
2322 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2323 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002324 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002325 touchMinor = touchMajor;
2326 toolMinor = toolMajor;
2327 }
2328
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002329 mCalibration.applySizeScaleAndBias(touchMajor);
2330 mCalibration.applySizeScaleAndBias(touchMinor);
2331 mCalibration.applySizeScaleAndBias(toolMajor);
2332 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002333 size *= mSizeScale;
2334 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002335 case Calibration::SizeCalibration::DEFAULT:
2336 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2337 break;
2338 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002339 touchMajor = 0;
2340 touchMinor = 0;
2341 toolMajor = 0;
2342 toolMinor = 0;
2343 size = 0;
2344 break;
2345 }
2346
2347 // Pressure
2348 float pressure;
2349 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002350 case Calibration::PressureCalibration::PHYSICAL:
2351 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002352 pressure = in.pressure * mPressureScale;
2353 break;
2354 default:
2355 pressure = in.isHovering ? 0 : 1;
2356 break;
2357 }
2358
2359 // Tilt and Orientation
2360 float tilt;
2361 float orientation;
2362 if (mHaveTilt) {
2363 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2364 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002365 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002366 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2367 } else {
2368 tilt = 0;
2369
2370 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002371 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002372 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002373 break;
Michael Wright227c5542020-07-02 18:30:52 +01002374 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002375 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2376 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2377 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002378 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002379 float confidence = hypotf(c1, c2);
2380 float scale = 1.0f + confidence / 16.0f;
2381 touchMajor *= scale;
2382 touchMinor /= scale;
2383 toolMajor *= scale;
2384 toolMinor /= scale;
2385 } else {
2386 orientation = 0;
2387 }
2388 break;
2389 }
2390 default:
2391 orientation = 0;
2392 }
2393 }
2394
2395 // Distance
2396 float distance;
2397 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002398 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002399 distance = in.distance * mDistanceScale;
2400 break;
2401 default:
2402 distance = 0;
2403 }
2404
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002405 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2406 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002407 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2408 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002409
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002410 // Write output coords.
2411 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2412 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002413 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2414 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002415 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2416 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2417 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2418 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2419 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2420 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2421 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002422 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2423 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002424
Chris Ye364fdb52020-08-05 15:07:56 -07002425 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002426 uint32_t id = in.id;
2427 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2428 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2429 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002430 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2431 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002432 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2433 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2434 }
2435
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002436 // Write output properties.
2437 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002438 properties.clear();
2439 properties.id = id;
2440 properties.toolType = in.toolType;
2441
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002442 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002443 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002444 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002445 }
2446}
2447
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002448std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2449 uint32_t policyFlags,
2450 PointerUsage pointerUsage) {
2451 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002452 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002453 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002454 mPointerUsage = pointerUsage;
2455 }
2456
2457 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002458 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002459 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002460 break;
Michael Wright227c5542020-07-02 18:30:52 +01002461 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002462 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002463 break;
Michael Wright227c5542020-07-02 18:30:52 +01002464 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002465 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002466 break;
Michael Wright227c5542020-07-02 18:30:52 +01002467 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002468 break;
2469 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002470 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002471}
2472
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002473std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2474 uint32_t policyFlags) {
2475 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002476 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002477 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002478 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002479 break;
Michael Wright227c5542020-07-02 18:30:52 +01002480 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002481 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002482 break;
Michael Wright227c5542020-07-02 18:30:52 +01002483 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002484 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002485 break;
Michael Wright227c5542020-07-02 18:30:52 +01002486 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002487 break;
2488 }
2489
Michael Wright227c5542020-07-02 18:30:52 +01002490 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002491 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002492}
2493
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002494std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2495 uint32_t policyFlags,
2496 bool isTimeout) {
2497 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002498 // Update current gesture coordinates.
2499 bool cancelPreviousGesture, finishPreviousGesture;
2500 bool sendEvents =
2501 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2502 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002503 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002504 }
2505 if (finishPreviousGesture) {
2506 cancelPreviousGesture = false;
2507 }
2508
2509 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002510 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002511 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002512 if (finishPreviousGesture || cancelPreviousGesture) {
2513 mPointerController->clearSpots();
2514 }
2515
Michael Wright227c5542020-07-02 18:30:52 +01002516 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002517 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2518 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002519 mPointerGesture.currentGestureIdBits,
2520 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002521 }
2522 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002523 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002524 }
2525
2526 // Show or hide the pointer if needed.
2527 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002528 case PointerGesture::Mode::NEUTRAL:
2529 case PointerGesture::Mode::QUIET:
2530 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2531 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002532 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002533 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002534 }
2535 break;
Michael Wright227c5542020-07-02 18:30:52 +01002536 case PointerGesture::Mode::TAP:
2537 case PointerGesture::Mode::TAP_DRAG:
2538 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2539 case PointerGesture::Mode::HOVER:
2540 case PointerGesture::Mode::PRESS:
2541 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002542 // Unfade the pointer when the current gesture manipulates the
2543 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002544 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002545 break;
Michael Wright227c5542020-07-02 18:30:52 +01002546 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002547 // Fade the pointer when the current gesture manipulates a different
2548 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002549 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002550 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002551 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002552 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002553 }
2554 break;
2555 }
2556
2557 // Send events!
2558 int32_t metaState = getContext()->getGlobalMetaState();
2559 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002560 const MotionClassification classification =
2561 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2562 ? MotionClassification::TWO_FINGER_SWIPE
2563 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002564
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002565 uint32_t flags = 0;
2566
2567 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2568 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2569 }
2570
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002571 // Update last coordinates of pointers that have moved so that we observe the new
2572 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002573 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2574 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2575 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2576 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2577 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2578 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002579 bool moveNeeded = false;
2580 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2581 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2582 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2583 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2584 mPointerGesture.lastGestureIdBits.value);
2585 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2586 mPointerGesture.currentGestureCoords,
2587 mPointerGesture.currentGestureIdToIndex,
2588 mPointerGesture.lastGestureProperties,
2589 mPointerGesture.lastGestureCoords,
2590 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2591 if (buttonState != mLastCookedState.buttonState) {
2592 moveNeeded = true;
2593 }
2594 }
2595
2596 // Send motion events for all pointers that went up or were canceled.
2597 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2598 if (!dispatchedGestureIdBits.isEmpty()) {
2599 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002600 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002601 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002602 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002603 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2604 mPointerGesture.lastGestureProperties,
2605 mPointerGesture.lastGestureCoords,
2606 mPointerGesture.lastGestureIdToIndex,
2607 dispatchedGestureIdBits, -1, 0, 0,
2608 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002609
2610 dispatchedGestureIdBits.clear();
2611 } else {
2612 BitSet32 upGestureIdBits;
2613 if (finishPreviousGesture) {
2614 upGestureIdBits = dispatchedGestureIdBits;
2615 } else {
2616 upGestureIdBits.value =
2617 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2618 }
2619 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002620 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2621 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2622 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2623 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2624 readTime);
2625 }
2626 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002627 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2628 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2629 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2630 mPointerGesture.lastGestureProperties,
2631 mPointerGesture.lastGestureCoords,
2632 mPointerGesture.lastGestureIdToIndex,
2633 dispatchedGestureIdBits, id, 0, 0,
2634 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002635
2636 dispatchedGestureIdBits.clearBit(id);
2637 }
2638 }
2639 }
2640
2641 // Send motion events for all pointers that moved.
2642 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002643 out.push_back(
2644 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2645 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2646 mPointerGesture.currentGestureProperties,
2647 mPointerGesture.currentGestureCoords,
2648 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2649 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002650 }
2651
2652 // Send motion events for all pointers that went down.
2653 if (down) {
2654 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2655 ~dispatchedGestureIdBits.value);
2656 while (!downGestureIdBits.isEmpty()) {
2657 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2658 dispatchedGestureIdBits.markBit(id);
2659
2660 if (dispatchedGestureIdBits.count() == 1) {
2661 mPointerGesture.downTime = when;
2662 }
2663
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002664 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2665 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2666 buttonState, 0, mPointerGesture.currentGestureProperties,
2667 mPointerGesture.currentGestureCoords,
2668 mPointerGesture.currentGestureIdToIndex,
2669 dispatchedGestureIdBits, id, 0, 0,
2670 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002671 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2672 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2673 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2674 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2675 readTime);
2676 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002677 }
2678 }
2679
2680 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002681 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002682 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2683 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2684 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2685 mPointerGesture.currentGestureProperties,
2686 mPointerGesture.currentGestureCoords,
2687 mPointerGesture.currentGestureIdToIndex,
2688 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2689 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002690 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2691 // Synthesize a hover move event after all pointers go up to indicate that
2692 // the pointer is hovering again even if the user is not currently touching
2693 // the touch pad. This ensures that a view will receive a fresh hover enter
2694 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002695 float x, y;
2696 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002697
2698 PointerProperties pointerProperties;
2699 pointerProperties.clear();
2700 pointerProperties.id = 0;
2701 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2702
2703 PointerCoords pointerCoords;
2704 pointerCoords.clear();
2705 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2706 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2707
2708 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002709 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2710 mSource, displayId, policyFlags,
2711 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2712 buttonState, MotionClassification::NONE,
2713 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2714 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2715 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002716 }
2717
2718 // Update state.
2719 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2720 if (!down) {
2721 mPointerGesture.lastGestureIdBits.clear();
2722 } else {
2723 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2724 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2725 uint32_t id = idBits.clearFirstMarkedBit();
2726 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2727 mPointerGesture.lastGestureProperties[index].copyFrom(
2728 mPointerGesture.currentGestureProperties[index]);
2729 mPointerGesture.lastGestureCoords[index].copyFrom(
2730 mPointerGesture.currentGestureCoords[index]);
2731 mPointerGesture.lastGestureIdToIndex[id] = index;
2732 }
2733 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002734 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002735}
2736
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002737std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2738 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002739 const MotionClassification classification =
2740 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2741 ? MotionClassification::TWO_FINGER_SWIPE
2742 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002743 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002744 // Cancel previously dispatches pointers.
2745 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2746 int32_t metaState = getContext()->getGlobalMetaState();
2747 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002748 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002749 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2750 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002751 mPointerGesture.lastGestureProperties,
2752 mPointerGesture.lastGestureCoords,
2753 mPointerGesture.lastGestureIdToIndex,
2754 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2755 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002756 }
2757
2758 // Reset the current pointer gesture.
2759 mPointerGesture.reset();
2760 mPointerVelocityControl.reset();
2761
2762 // Remove any current spots.
2763 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002764 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002765 mPointerController->clearSpots();
2766 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002767 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002768}
2769
2770bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2771 bool* outFinishPreviousGesture, bool isTimeout) {
2772 *outCancelPreviousGesture = false;
2773 *outFinishPreviousGesture = false;
2774
2775 // Handle TAP timeout.
2776 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002777 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002778
Michael Wright227c5542020-07-02 18:30:52 +01002779 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002780 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2781 // The tap/drag timeout has not yet expired.
2782 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2783 mConfig.pointerGestureTapDragInterval);
2784 } else {
2785 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002786 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002787 *outFinishPreviousGesture = true;
2788
2789 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002790 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002791 mPointerGesture.currentGestureIdBits.clear();
2792
2793 mPointerVelocityControl.reset();
2794 return true;
2795 }
2796 }
2797
2798 // We did not handle this timeout.
2799 return false;
2800 }
2801
2802 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2803 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2804
2805 // Update the velocity tracker.
2806 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002807 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002808 uint32_t id = idBits.clearFirstMarkedBit();
2809 const RawPointerData::Pointer& pointer =
2810 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002811 const float x = pointer.x * mPointerXMovementScale;
2812 const float y = pointer.y * mPointerYMovementScale;
2813 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2814 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002815 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002816 }
2817
2818 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2819 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002820 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2821 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2822 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002823 mPointerGesture.resetTap();
2824 }
2825
2826 // Pick a new active touch id if needed.
2827 // Choose an arbitrary pointer that just went down, if there is one.
2828 // Otherwise choose an arbitrary remaining pointer.
2829 // This guarantees we always have an active touch id when there is at least one pointer.
2830 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002831 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002832 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002833 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002834 mPointerGesture.firstTouchTime = when;
2835 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002836 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2837 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2838 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2839 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002840 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002841 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002842
2843 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002844 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002845 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002846 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2847 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2848 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002849 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002850 *outFinishPreviousGesture = true;
2851 }
2852
2853 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002854 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002855 mPointerGesture.currentGestureIdBits.clear();
2856
2857 mPointerVelocityControl.reset();
2858 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2859 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2860 // The pointer follows the active touch point.
2861 // Emit DOWN, MOVE, UP events at the pointer location.
2862 //
2863 // Only the active touch matters; other fingers are ignored. This policy helps
2864 // to handle the case where the user places a second finger on the touch pad
2865 // to apply the necessary force to depress an integrated button below the surface.
2866 // We don't want the second finger to be delivered to applications.
2867 //
2868 // For this to work well, we need to make sure to track the pointer that is really
2869 // active. If the user first puts one finger down to click then adds another
2870 // finger to drag then the active pointer should switch to the finger that is
2871 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002872 ALOGD_IF(DEBUG_GESTURES,
2873 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2874 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002875 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002876 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002877 *outFinishPreviousGesture = true;
2878 mPointerGesture.activeGestureId = 0;
2879 }
2880
2881 // Switch pointers if needed.
2882 // Find the fastest pointer and follow it.
2883 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002884 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002885 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002886 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002887 ALOGD_IF(DEBUG_GESTURES,
2888 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2889 "bestSpeed=%0.3f",
2890 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002891 }
2892 }
2893
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002894 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002895 // When using spots, the click will occur at the position of the anchor
2896 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002897 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002898 } else {
2899 mPointerVelocityControl.reset();
2900 }
2901
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002902 float x, y;
2903 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002904
Michael Wright227c5542020-07-02 18:30:52 +01002905 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002906 mPointerGesture.currentGestureIdBits.clear();
2907 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2908 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2909 mPointerGesture.currentGestureProperties[0].clear();
2910 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2911 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2912 mPointerGesture.currentGestureCoords[0].clear();
2913 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2914 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2915 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2916 } else if (currentFingerCount == 0) {
2917 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002918 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002919 *outFinishPreviousGesture = true;
2920 }
2921
2922 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2923 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2924 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002925 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2926 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002927 lastFingerCount == 1) {
2928 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002929 float x, y;
2930 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002931 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2932 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002933 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002934
2935 mPointerGesture.tapUpTime = when;
2936 getContext()->requestTimeoutAtTime(when +
2937 mConfig.pointerGestureTapDragInterval);
2938
2939 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002940 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002941 mPointerGesture.currentGestureIdBits.clear();
2942 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2943 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2944 mPointerGesture.currentGestureProperties[0].clear();
2945 mPointerGesture.currentGestureProperties[0].id =
2946 mPointerGesture.activeGestureId;
2947 mPointerGesture.currentGestureProperties[0].toolType =
2948 AMOTION_EVENT_TOOL_TYPE_FINGER;
2949 mPointerGesture.currentGestureCoords[0].clear();
2950 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2951 mPointerGesture.tapX);
2952 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2953 mPointerGesture.tapY);
2954 mPointerGesture.currentGestureCoords[0]
2955 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2956
2957 tapped = true;
2958 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002959 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2960 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002961 }
2962 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002963 if (DEBUG_GESTURES) {
2964 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2965 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2966 (when - mPointerGesture.tapDownTime) * 0.000001f);
2967 } else {
2968 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2969 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002970 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002971 }
2972 }
2973
2974 mPointerVelocityControl.reset();
2975
2976 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002977 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002978 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002979 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002980 mPointerGesture.currentGestureIdBits.clear();
2981 }
2982 } else if (currentFingerCount == 1) {
2983 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2984 // The pointer follows the active touch point.
2985 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2986 // When in TAP_DRAG, emit MOVE events at the pointer location.
2987 ALOG_ASSERT(activeTouchId >= 0);
2988
Michael Wright227c5542020-07-02 18:30:52 +01002989 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2990 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002991 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002992 float x, y;
2993 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002994 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2995 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002996 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002997 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002998 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2999 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003000 }
3001 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003002 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
3003 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003004 }
Michael Wright227c5542020-07-02 18:30:52 +01003005 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
3006 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003007 }
3008
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003009 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003010 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00003011 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003012 } else {
3013 mPointerVelocityControl.reset();
3014 }
3015
3016 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003017 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00003018 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003019 down = true;
3020 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003021 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003022 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003023 *outFinishPreviousGesture = true;
3024 }
3025 mPointerGesture.activeGestureId = 0;
3026 down = false;
3027 }
3028
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003029 float x, y;
3030 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003031
3032 mPointerGesture.currentGestureIdBits.clear();
3033 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3034 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3035 mPointerGesture.currentGestureProperties[0].clear();
3036 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3037 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3038 mPointerGesture.currentGestureCoords[0].clear();
3039 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3040 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3041 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3042 down ? 1.0f : 0.0f);
3043
3044 if (lastFingerCount == 0 && currentFingerCount != 0) {
3045 mPointerGesture.resetTap();
3046 mPointerGesture.tapDownTime = when;
3047 mPointerGesture.tapX = x;
3048 mPointerGesture.tapY = y;
3049 }
3050 } else {
3051 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003052 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003053 }
3054
3055 mPointerController->setButtonState(mCurrentRawState.buttonState);
3056
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003057 if (DEBUG_GESTURES) {
3058 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3059 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3060 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3061 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3062 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3063 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3064 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3065 uint32_t id = idBits.clearFirstMarkedBit();
3066 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3067 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3068 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3069 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3070 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3071 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3072 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3073 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3074 }
3075 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3076 uint32_t id = idBits.clearFirstMarkedBit();
3077 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3078 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3079 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3080 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3081 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3082 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3083 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3084 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3085 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003086 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003087 return true;
3088}
3089
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003090bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3091 if (mPointerGesture.activeTouchId < 0) {
3092 mPointerGesture.resetQuietTime();
3093 return false;
3094 }
3095
3096 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3097 return true;
3098 }
3099
3100 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3101 bool isQuietTime = false;
3102 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3103 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3104 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3105 currentFingerCount < 2) {
3106 // Enter quiet time when exiting swipe or freeform state.
3107 // This is to prevent accidentally entering the hover state and flinging the
3108 // pointer when finishing a swipe and there is still one pointer left onscreen.
3109 isQuietTime = true;
3110 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3111 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3112 // Enter quiet time when releasing the button and there are still two or more
3113 // fingers down. This may indicate that one finger was used to press the button
3114 // but it has not gone up yet.
3115 isQuietTime = true;
3116 }
3117 if (isQuietTime) {
3118 mPointerGesture.quietTime = when;
3119 }
3120 return isQuietTime;
3121}
3122
3123std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3124 int32_t bestId = -1;
3125 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3126 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3127 uint32_t id = idBits.clearFirstMarkedBit();
3128 std::optional<float> vx =
3129 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3130 std::optional<float> vy =
3131 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3132 if (vx && vy) {
3133 float speed = hypotf(*vx, *vy);
3134 if (speed > bestSpeed) {
3135 bestId = id;
3136 bestSpeed = speed;
3137 }
3138 }
3139 }
3140 return std::make_pair(bestId, bestSpeed);
3141}
3142
3143void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3144 bool* finishPreviousGesture) {
3145 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3146 // to move before deciding what to do.
3147 //
3148 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3149 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3150 // just a press or long-press at the pointer location.
3151 //
3152 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3153 // pointer location.
3154 //
3155 // When the two fingers move enough or when additional fingers are added, we make a decision to
3156 // transition into SWIPE or FREEFORM mode accordingly.
3157 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3158 ALOG_ASSERT(activeTouchId >= 0);
3159
3160 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3161 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3162 bool settled =
3163 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3164 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3165 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3166 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3167 *finishPreviousGesture = true;
3168 } else if (!settled && currentFingerCount > lastFingerCount) {
3169 // Additional pointers have gone down but not yet settled.
3170 // Reset the gesture.
3171 ALOGD_IF(DEBUG_GESTURES,
3172 "Gestures: Resetting gesture since additional pointers went down for "
3173 "MULTITOUCH, settle time remaining %0.3fms",
3174 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3175 when) * 0.000001f);
3176 *cancelPreviousGesture = true;
3177 } else {
3178 // Continue previous gesture.
3179 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3180 }
3181
3182 if (*finishPreviousGesture || *cancelPreviousGesture) {
3183 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3184 mPointerGesture.activeGestureId = 0;
3185 mPointerGesture.referenceIdBits.clear();
3186 mPointerVelocityControl.reset();
3187
3188 // Use the centroid and pointer location as the reference points for the gesture.
3189 ALOGD_IF(DEBUG_GESTURES,
3190 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3191 "%0.3fms",
3192 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3193 when) * 0.000001f);
3194 mCurrentRawState.rawPointerData
3195 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3196 &mPointerGesture.referenceTouchY);
3197 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3198 &mPointerGesture.referenceGestureY);
3199 }
3200
3201 // Clear the reference deltas for fingers not yet included in the reference calculation.
3202 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3203 ~mPointerGesture.referenceIdBits.value);
3204 !idBits.isEmpty();) {
3205 uint32_t id = idBits.clearFirstMarkedBit();
3206 mPointerGesture.referenceDeltas[id].dx = 0;
3207 mPointerGesture.referenceDeltas[id].dy = 0;
3208 }
3209 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3210
3211 // Add delta for all fingers and calculate a common movement delta.
3212 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3213 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3214 mCurrentCookedState.fingerIdBits.value);
3215 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3216 bool first = (idBits == commonIdBits);
3217 uint32_t id = idBits.clearFirstMarkedBit();
3218 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3219 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3220 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3221 delta.dx += cpd.x - lpd.x;
3222 delta.dy += cpd.y - lpd.y;
3223
3224 if (first) {
3225 commonDeltaRawX = delta.dx;
3226 commonDeltaRawY = delta.dy;
3227 } else {
3228 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3229 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3230 }
3231 }
3232
3233 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3234 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3235 float dist[MAX_POINTER_ID + 1];
3236 int32_t distOverThreshold = 0;
3237 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3238 uint32_t id = idBits.clearFirstMarkedBit();
3239 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3240 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3241 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3242 distOverThreshold += 1;
3243 }
3244 }
3245
3246 // Only transition when at least two pointers have moved further than
3247 // the minimum distance threshold.
3248 if (distOverThreshold >= 2) {
3249 if (currentFingerCount > 2) {
3250 // There are more than two pointers, switch to FREEFORM.
3251 ALOGD_IF(DEBUG_GESTURES,
3252 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3253 currentFingerCount);
3254 *cancelPreviousGesture = true;
3255 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3256 } else {
3257 // There are exactly two pointers.
3258 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3259 uint32_t id1 = idBits.clearFirstMarkedBit();
3260 uint32_t id2 = idBits.firstMarkedBit();
3261 const RawPointerData::Pointer& p1 =
3262 mCurrentRawState.rawPointerData.pointerForId(id1);
3263 const RawPointerData::Pointer& p2 =
3264 mCurrentRawState.rawPointerData.pointerForId(id2);
3265 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3266 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3267 // There are two pointers but they are too far apart for a SWIPE,
3268 // switch to FREEFORM.
3269 ALOGD_IF(DEBUG_GESTURES,
3270 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3271 mutualDistance, mPointerGestureMaxSwipeWidth);
3272 *cancelPreviousGesture = true;
3273 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3274 } else {
3275 // There are two pointers. Wait for both pointers to start moving
3276 // before deciding whether this is a SWIPE or FREEFORM gesture.
3277 float dist1 = dist[id1];
3278 float dist2 = dist[id2];
3279 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3280 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3281 // Calculate the dot product of the displacement vectors.
3282 // When the vectors are oriented in approximately the same direction,
3283 // the angle betweeen them is near zero and the cosine of the angle
3284 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3285 // mag(v2).
3286 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3287 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3288 float dx1 = delta1.dx * mPointerXZoomScale;
3289 float dy1 = delta1.dy * mPointerYZoomScale;
3290 float dx2 = delta2.dx * mPointerXZoomScale;
3291 float dy2 = delta2.dy * mPointerYZoomScale;
3292 float dot = dx1 * dx2 + dy1 * dy2;
3293 float cosine = dot / (dist1 * dist2); // denominator always > 0
3294 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3295 // Pointers are moving in the same direction. Switch to SWIPE.
3296 ALOGD_IF(DEBUG_GESTURES,
3297 "Gestures: PRESS transitioned to SWIPE, "
3298 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3299 "cosine %0.3f >= %0.3f",
3300 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3301 mConfig.pointerGestureMultitouchMinDistance, cosine,
3302 mConfig.pointerGestureSwipeTransitionAngleCosine);
3303 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3304 } else {
3305 // Pointers are moving in different directions. Switch to FREEFORM.
3306 ALOGD_IF(DEBUG_GESTURES,
3307 "Gestures: PRESS transitioned to FREEFORM, "
3308 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3309 "cosine %0.3f < %0.3f",
3310 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3311 mConfig.pointerGestureMultitouchMinDistance, cosine,
3312 mConfig.pointerGestureSwipeTransitionAngleCosine);
3313 *cancelPreviousGesture = true;
3314 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3315 }
3316 }
3317 }
3318 }
3319 }
3320 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3321 // Switch from SWIPE to FREEFORM if additional pointers go down.
3322 // Cancel previous gesture.
3323 if (currentFingerCount > 2) {
3324 ALOGD_IF(DEBUG_GESTURES,
3325 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3326 currentFingerCount);
3327 *cancelPreviousGesture = true;
3328 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3329 }
3330 }
3331
3332 // Move the reference points based on the overall group motion of the fingers
3333 // except in PRESS mode while waiting for a transition to occur.
3334 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3335 (commonDeltaRawX || commonDeltaRawY)) {
3336 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3337 uint32_t id = idBits.clearFirstMarkedBit();
3338 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3339 delta.dx = 0;
3340 delta.dy = 0;
3341 }
3342
3343 mPointerGesture.referenceTouchX += commonDeltaRawX;
3344 mPointerGesture.referenceTouchY += commonDeltaRawY;
3345
3346 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3347 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3348
3349 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3350 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3351
3352 mPointerGesture.referenceGestureX += commonDeltaX;
3353 mPointerGesture.referenceGestureY += commonDeltaY;
3354 }
3355
3356 // Report gestures.
3357 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3358 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3359 // PRESS or SWIPE mode.
3360 ALOGD_IF(DEBUG_GESTURES,
3361 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3362 "currentTouchPointerCount=%d",
3363 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3364 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3365
3366 mPointerGesture.currentGestureIdBits.clear();
3367 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3368 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3369 mPointerGesture.currentGestureProperties[0].clear();
3370 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3371 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3372 mPointerGesture.currentGestureCoords[0].clear();
3373 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3374 mPointerGesture.referenceGestureX);
3375 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3376 mPointerGesture.referenceGestureY);
3377 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3378 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3379 float xOffset = static_cast<float>(commonDeltaRawX) /
3380 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3381 float yOffset = static_cast<float>(commonDeltaRawY) /
3382 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3383 mPointerGesture.currentGestureCoords[0]
3384 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3385 mPointerGesture.currentGestureCoords[0]
3386 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3387 }
3388 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3389 // FREEFORM mode.
3390 ALOGD_IF(DEBUG_GESTURES,
3391 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3392 "currentTouchPointerCount=%d",
3393 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3394 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3395
3396 mPointerGesture.currentGestureIdBits.clear();
3397
3398 BitSet32 mappedTouchIdBits;
3399 BitSet32 usedGestureIdBits;
3400 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3401 // Initially, assign the active gesture id to the active touch point
3402 // if there is one. No other touch id bits are mapped yet.
3403 if (!*cancelPreviousGesture) {
3404 mappedTouchIdBits.markBit(activeTouchId);
3405 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3406 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3407 mPointerGesture.activeGestureId;
3408 } else {
3409 mPointerGesture.activeGestureId = -1;
3410 }
3411 } else {
3412 // Otherwise, assume we mapped all touches from the previous frame.
3413 // Reuse all mappings that are still applicable.
3414 mappedTouchIdBits.value =
3415 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3416 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3417
3418 // Check whether we need to choose a new active gesture id because the
3419 // current went went up.
3420 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3421 ~mCurrentCookedState.fingerIdBits.value);
3422 !upTouchIdBits.isEmpty();) {
3423 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3424 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3425 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3426 mPointerGesture.activeGestureId = -1;
3427 break;
3428 }
3429 }
3430 }
3431
3432 ALOGD_IF(DEBUG_GESTURES,
3433 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3434 "activeGestureId=%d",
3435 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3436
3437 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3438 for (uint32_t i = 0; i < currentFingerCount; i++) {
3439 uint32_t touchId = idBits.clearFirstMarkedBit();
3440 uint32_t gestureId;
3441 if (!mappedTouchIdBits.hasBit(touchId)) {
3442 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3443 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3444 ALOGD_IF(DEBUG_GESTURES,
3445 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3446 gestureId);
3447 } else {
3448 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3449 ALOGD_IF(DEBUG_GESTURES,
3450 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3451 touchId, gestureId);
3452 }
3453 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3454 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3455
3456 const RawPointerData::Pointer& pointer =
3457 mCurrentRawState.rawPointerData.pointerForId(touchId);
3458 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3459 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3460 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3461
3462 mPointerGesture.currentGestureProperties[i].clear();
3463 mPointerGesture.currentGestureProperties[i].id = gestureId;
3464 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3465 mPointerGesture.currentGestureCoords[i].clear();
3466 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3467 mPointerGesture.referenceGestureX +
3468 deltaX);
3469 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3470 mPointerGesture.referenceGestureY +
3471 deltaY);
3472 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3473 }
3474
3475 if (mPointerGesture.activeGestureId < 0) {
3476 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3477 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3478 mPointerGesture.activeGestureId);
3479 }
3480 }
3481}
3482
Harry Cutts714d1ad2022-08-24 16:36:43 +00003483void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3484 const RawPointerData::Pointer& currentPointer =
3485 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3486 const RawPointerData::Pointer& lastPointer =
3487 mLastRawState.rawPointerData.pointerForId(pointerId);
3488 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3489 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3490
3491 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3492 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3493
3494 mPointerController->move(deltaX, deltaY);
3495}
3496
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003497std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3498 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003499 mPointerSimple.currentCoords.clear();
3500 mPointerSimple.currentProperties.clear();
3501
3502 bool down, hovering;
3503 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3504 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3505 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003506 mPointerController
3507 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3508 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003509
3510 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3511 down = !hovering;
3512
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003513 float x, y;
3514 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003515 mPointerSimple.currentCoords.copyFrom(
3516 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3517 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3518 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3519 mPointerSimple.currentProperties.id = 0;
3520 mPointerSimple.currentProperties.toolType =
3521 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3522 } else {
3523 down = false;
3524 hovering = false;
3525 }
3526
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003527 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003528}
3529
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003530std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3531 uint32_t policyFlags) {
3532 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003533}
3534
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003535std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3536 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003537 mPointerSimple.currentCoords.clear();
3538 mPointerSimple.currentProperties.clear();
3539
3540 bool down, hovering;
3541 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3542 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003543 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003544 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003545 } else {
3546 mPointerVelocityControl.reset();
3547 }
3548
3549 down = isPointerDown(mCurrentRawState.buttonState);
3550 hovering = !down;
3551
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003552 float x, y;
3553 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003554 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003555 mPointerSimple.currentCoords.copyFrom(
3556 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3557 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3558 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3559 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3560 hovering ? 0.0f : 1.0f);
3561 mPointerSimple.currentProperties.id = 0;
3562 mPointerSimple.currentProperties.toolType =
3563 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3564 } else {
3565 mPointerVelocityControl.reset();
3566
3567 down = false;
3568 hovering = false;
3569 }
3570
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003571 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003572}
3573
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003574std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3575 uint32_t policyFlags) {
3576 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003577
3578 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003579
3580 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003581}
3582
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003583std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3584 uint32_t policyFlags, bool down,
3585 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003586 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3587 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003588 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003589 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003590
3591 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003592 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003593 mPointerController->clearSpots();
3594 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003595 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003596 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003597 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003598 }
Garfield Tan9514d782020-11-10 16:37:23 -08003599 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003600
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003601 float xCursorPosition, yCursorPosition;
3602 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003603
3604 if (mPointerSimple.down && !down) {
3605 mPointerSimple.down = false;
3606
3607 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003608 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3609 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3610 0, metaState, mLastRawState.buttonState,
3611 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3612 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3613 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3614 yCursorPosition, mPointerSimple.downTime,
3615 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003616 }
3617
3618 if (mPointerSimple.hovering && !hovering) {
3619 mPointerSimple.hovering = false;
3620
3621 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003622 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3623 mSource, displayId, policyFlags,
3624 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3625 mLastRawState.buttonState, MotionClassification::NONE,
3626 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3627 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3628 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3629 yCursorPosition, mPointerSimple.downTime,
3630 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003631 }
3632
3633 if (down) {
3634 if (!mPointerSimple.down) {
3635 mPointerSimple.down = true;
3636 mPointerSimple.downTime = when;
3637
3638 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003639 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3640 mSource, displayId, policyFlags,
3641 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3642 mCurrentRawState.buttonState, MotionClassification::NONE,
3643 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3644 &mPointerSimple.currentProperties,
3645 &mPointerSimple.currentCoords, mOrientedXPrecision,
3646 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3647 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003648 }
3649
3650 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003651 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3652 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3653 0, 0, metaState, mCurrentRawState.buttonState,
3654 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3655 &mPointerSimple.currentProperties,
3656 &mPointerSimple.currentCoords, mOrientedXPrecision,
3657 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3658 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003659 }
3660
3661 if (hovering) {
3662 if (!mPointerSimple.hovering) {
3663 mPointerSimple.hovering = true;
3664
3665 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003666 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3667 mSource, displayId, policyFlags,
3668 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3669 mCurrentRawState.buttonState, MotionClassification::NONE,
3670 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3671 &mPointerSimple.currentProperties,
3672 &mPointerSimple.currentCoords, mOrientedXPrecision,
3673 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3674 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003675 }
3676
3677 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003678 out.push_back(
3679 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3680 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3681 metaState, mCurrentRawState.buttonState,
3682 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3683 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3684 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3685 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003686 }
3687
3688 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3689 float vscroll = mCurrentRawState.rawVScroll;
3690 float hscroll = mCurrentRawState.rawHScroll;
3691 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3692 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3693
3694 // Send scroll.
3695 PointerCoords pointerCoords;
3696 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3697 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3698 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3699
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003700 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3701 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3702 0, 0, metaState, mCurrentRawState.buttonState,
3703 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3704 &mPointerSimple.currentProperties, &pointerCoords,
3705 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3706 yCursorPosition, mPointerSimple.downTime,
3707 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003708 }
3709
3710 // Save state.
3711 if (down || hovering) {
3712 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3713 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003714 mPointerSimple.displayId = displayId;
3715 mPointerSimple.source = mSource;
3716 mPointerSimple.lastCursorX = xCursorPosition;
3717 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003718 } else {
3719 mPointerSimple.reset();
3720 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003721 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003722}
3723
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003724std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3725 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003726 std::list<NotifyArgs> out;
3727 if (mPointerSimple.down || mPointerSimple.hovering) {
3728 int32_t metaState = getContext()->getGlobalMetaState();
3729 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3730 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3731 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3732 metaState, mLastRawState.buttonState,
3733 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3734 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3735 mOrientedXPrecision, mOrientedYPrecision,
3736 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3737 mPointerSimple.downTime,
3738 /* videoFrames */ {}));
3739 if (mPointerController != nullptr) {
3740 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3741 }
3742 }
3743 mPointerSimple.reset();
3744 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003745}
3746
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003747static bool isStylusEvent(uint32_t source, int32_t action, const PointerProperties* properties) {
3748 if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
3749 return false;
3750 }
3751 const auto actionIndex = action >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3752 return isStylusToolType(properties[actionIndex].toolType);
3753}
3754
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003755NotifyMotionArgs TouchInputMapper::dispatchMotion(
3756 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3757 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003758 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3759 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003760 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003761 PointerCoords pointerCoords[MAX_POINTERS];
3762 PointerProperties pointerProperties[MAX_POINTERS];
3763 uint32_t pointerCount = 0;
3764 while (!idBits.isEmpty()) {
3765 uint32_t id = idBits.clearFirstMarkedBit();
3766 uint32_t index = idToIndex[id];
3767 pointerProperties[pointerCount].copyFrom(properties[index]);
3768 pointerCoords[pointerCount].copyFrom(coords[index]);
3769
3770 if (changedId >= 0 && id == uint32_t(changedId)) {
3771 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3772 }
3773
3774 pointerCount += 1;
3775 }
3776
3777 ALOG_ASSERT(pointerCount != 0);
3778
3779 if (changedId >= 0 && pointerCount == 1) {
3780 // Replace initial down and final up action.
3781 // We can compare the action without masking off the changed pointer index
3782 // because we know the index is 0.
3783 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3784 action = AMOTION_EVENT_ACTION_DOWN;
3785 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003786 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3787 action = AMOTION_EVENT_ACTION_CANCEL;
3788 } else {
3789 action = AMOTION_EVENT_ACTION_UP;
3790 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003791 } else {
3792 // Can't happen.
3793 ALOG_ASSERT(false);
3794 }
3795 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003796
3797 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3798 const bool showDirectStylusPointer = mConfig.stylusPointerIconEnabled &&
3799 mDeviceMode == DeviceMode::DIRECT && isStylusEvent(source, action, pointerProperties) &&
Seunghwan Choi356026c2023-02-01 14:37:25 +09003800 mPointerController && displayId != ADISPLAY_ID_NONE &&
3801 displayId == mPointerController->getDisplayId();
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003802 if (showDirectStylusPointer) {
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003803 switch (action & AMOTION_EVENT_ACTION_MASK) {
3804 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3805 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3806 mPointerController->setPresentation(
Seunghwan Choi75789cd2023-01-13 20:31:59 +09003807 PointerControllerInterface::Presentation::STYLUS_HOVER);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003808 mPointerController
3809 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[0].getX(),
3810 mCurrentCookedState.cookedPointerData.pointerCoords[0]
3811 .getY());
3812 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3813 break;
3814 case AMOTION_EVENT_ACTION_HOVER_EXIT:
3815 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
3816 break;
3817 }
3818 }
3819
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003820 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3821 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003822 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003823 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003824 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003825 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003826 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003827 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003828 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003829 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3830 policyFlags, action, actionButton, flags, metaState, buttonState,
3831 classification, edgeFlags, pointerCount, pointerProperties,
3832 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3833 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003834}
3835
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003836std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3837 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003838 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3839 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003840 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003841}
3842
Prabir Pradhan1728b212021-10-19 16:00:03 -07003843bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003844 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003845 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003846 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003847}
3848
3849const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3850 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003851 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3852 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3853 "left=%d, top=%d, right=%d, bottom=%d",
3854 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3855 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003856
3857 if (virtualKey.isHit(x, y)) {
3858 return &virtualKey;
3859 }
3860 }
3861
3862 return nullptr;
3863}
3864
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003865void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3866 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3867 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003868
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003869 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003870
3871 if (currentPointerCount == 0) {
3872 // No pointers to assign.
3873 return;
3874 }
3875
3876 if (lastPointerCount == 0) {
3877 // All pointers are new.
3878 for (uint32_t i = 0; i < currentPointerCount; i++) {
3879 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003880 current.rawPointerData.pointers[i].id = id;
3881 current.rawPointerData.idToIndex[id] = i;
3882 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003883 }
3884 return;
3885 }
3886
3887 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003888 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003889 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003890 uint32_t id = last.rawPointerData.pointers[0].id;
3891 current.rawPointerData.pointers[0].id = id;
3892 current.rawPointerData.idToIndex[id] = 0;
3893 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003894 return;
3895 }
3896
3897 // General case.
3898 // We build a heap of squared euclidean distances between current and last pointers
3899 // associated with the current and last pointer indices. Then, we find the best
3900 // match (by distance) for each current pointer.
3901 // The pointers must have the same tool type but it is possible for them to
3902 // transition from hovering to touching or vice-versa while retaining the same id.
3903 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3904
3905 uint32_t heapSize = 0;
3906 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3907 currentPointerIndex++) {
3908 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3909 lastPointerIndex++) {
3910 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003911 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003912 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003913 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003914 if (currentPointer.toolType == lastPointer.toolType) {
3915 int64_t deltaX = currentPointer.x - lastPointer.x;
3916 int64_t deltaY = currentPointer.y - lastPointer.y;
3917
3918 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3919
3920 // Insert new element into the heap (sift up).
3921 heap[heapSize].currentPointerIndex = currentPointerIndex;
3922 heap[heapSize].lastPointerIndex = lastPointerIndex;
3923 heap[heapSize].distance = distance;
3924 heapSize += 1;
3925 }
3926 }
3927 }
3928
3929 // Heapify
3930 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3931 startIndex -= 1;
3932 for (uint32_t parentIndex = startIndex;;) {
3933 uint32_t childIndex = parentIndex * 2 + 1;
3934 if (childIndex >= heapSize) {
3935 break;
3936 }
3937
3938 if (childIndex + 1 < heapSize &&
3939 heap[childIndex + 1].distance < heap[childIndex].distance) {
3940 childIndex += 1;
3941 }
3942
3943 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3944 break;
3945 }
3946
3947 swap(heap[parentIndex], heap[childIndex]);
3948 parentIndex = childIndex;
3949 }
3950 }
3951
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003952 if (DEBUG_POINTER_ASSIGNMENT) {
3953 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3954 for (size_t i = 0; i < heapSize; i++) {
3955 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3956 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3957 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003958 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003959
3960 // Pull matches out by increasing order of distance.
3961 // To avoid reassigning pointers that have already been matched, the loop keeps track
3962 // of which last and current pointers have been matched using the matchedXXXBits variables.
3963 // It also tracks the used pointer id bits.
3964 BitSet32 matchedLastBits(0);
3965 BitSet32 matchedCurrentBits(0);
3966 BitSet32 usedIdBits(0);
3967 bool first = true;
3968 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3969 while (heapSize > 0) {
3970 if (first) {
3971 // The first time through the loop, we just consume the root element of
3972 // the heap (the one with smallest distance).
3973 first = false;
3974 } else {
3975 // Previous iterations consumed the root element of the heap.
3976 // Pop root element off of the heap (sift down).
3977 heap[0] = heap[heapSize];
3978 for (uint32_t parentIndex = 0;;) {
3979 uint32_t childIndex = parentIndex * 2 + 1;
3980 if (childIndex >= heapSize) {
3981 break;
3982 }
3983
3984 if (childIndex + 1 < heapSize &&
3985 heap[childIndex + 1].distance < heap[childIndex].distance) {
3986 childIndex += 1;
3987 }
3988
3989 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3990 break;
3991 }
3992
3993 swap(heap[parentIndex], heap[childIndex]);
3994 parentIndex = childIndex;
3995 }
3996
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003997 if (DEBUG_POINTER_ASSIGNMENT) {
3998 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3999 for (size_t j = 0; j < heapSize; j++) {
4000 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
4001 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
4002 heap[j].distance);
4003 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004004 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004005 }
4006
4007 heapSize -= 1;
4008
4009 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
4010 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
4011
4012 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4013 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4014
4015 matchedCurrentBits.markBit(currentPointerIndex);
4016 matchedLastBits.markBit(lastPointerIndex);
4017
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004018 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4019 current.rawPointerData.pointers[currentPointerIndex].id = id;
4020 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4021 current.rawPointerData.markIdBit(id,
4022 current.rawPointerData.isHovering(
4023 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004024 usedIdBits.markBit(id);
4025
Harry Cutts45483602022-08-24 14:36:48 +00004026 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4027 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4028 ", distance=%" PRIu64,
4029 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004030 break;
4031 }
4032 }
4033
4034 // Assign fresh ids to pointers that were not matched in the process.
4035 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4036 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4037 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4038
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004039 current.rawPointerData.pointers[currentPointerIndex].id = id;
4040 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4041 current.rawPointerData.markIdBit(id,
4042 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004043
Harry Cutts45483602022-08-24 14:36:48 +00004044 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4045 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4046 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004047 }
4048}
4049
4050int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4051 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4052 return AKEY_STATE_VIRTUAL;
4053 }
4054
4055 for (const VirtualKey& virtualKey : mVirtualKeys) {
4056 if (virtualKey.keyCode == keyCode) {
4057 return AKEY_STATE_UP;
4058 }
4059 }
4060
4061 return AKEY_STATE_UNKNOWN;
4062}
4063
4064int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4065 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4066 return AKEY_STATE_VIRTUAL;
4067 }
4068
4069 for (const VirtualKey& virtualKey : mVirtualKeys) {
4070 if (virtualKey.scanCode == scanCode) {
4071 return AKEY_STATE_UP;
4072 }
4073 }
4074
4075 return AKEY_STATE_UNKNOWN;
4076}
4077
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004078bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4079 const std::vector<int32_t>& keyCodes,
4080 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004081 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004082 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004083 if (virtualKey.keyCode == keyCodes[i]) {
4084 outFlags[i] = 1;
4085 }
4086 }
4087 }
4088
4089 return true;
4090}
4091
4092std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4093 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004094 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004095 return std::make_optional(mPointerController->getDisplayId());
4096 } else {
4097 return std::make_optional(mViewport.displayId);
4098 }
4099 }
4100 return std::nullopt;
4101}
4102
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004103} // namespace android