blob: 943097ad257138142670a7df8783f07dd7d1c584 [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
Harry Cuttsd02ea102023-03-17 18:21:30 +0000137void TouchInputMapper::populateDeviceInfo(InputDeviceInfo& info) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700138 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
Harry Cuttsd02ea102023-03-17 18:21:30 +0000144 info.addMotionRange(mOrientedRanges.x);
145 info.addMotionRange(mOrientedRanges.y);
146 info.addMotionRange(mOrientedRanges.pressure);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000147
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;
Harry Cuttsd02ea102023-03-17 18:21:30 +0000156 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);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000160 }
161
162 if (mOrientedRanges.size) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000163 info.addMotionRange(*mOrientedRanges.size);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000164 }
165
166 if (mOrientedRanges.touchMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000167 info.addMotionRange(*mOrientedRanges.touchMajor);
168 info.addMotionRange(*mOrientedRanges.touchMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000169 }
170
171 if (mOrientedRanges.toolMajor) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000172 info.addMotionRange(*mOrientedRanges.toolMajor);
173 info.addMotionRange(*mOrientedRanges.toolMinor);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000174 }
175
176 if (mOrientedRanges.orientation) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000177 info.addMotionRange(*mOrientedRanges.orientation);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000178 }
179
180 if (mOrientedRanges.distance) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000181 info.addMotionRange(*mOrientedRanges.distance);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000182 }
183
184 if (mOrientedRanges.tilt) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000185 info.addMotionRange(*mOrientedRanges.tilt);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000186 }
187
188 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000189 info.addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000190 }
191 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
Harry Cuttsd02ea102023-03-17 18:21:30 +0000192 info.addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000193 }
Harry Cuttsd02ea102023-03-17 18:21:30 +0000194 info.setButtonUnderPad(mParameters.hasButtonUnderPad);
195 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
Harry Cuttsf13161a2023-03-08 14:15:49 +0000369 const PropertyMap& config = getDeviceContext().getConfiguration();
370 std::optional<std::string> gestureModeString = config.getString("touch.gestureMode");
371 if (gestureModeString.has_value()) {
372 if (*gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100373 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000374 } else if (*gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100375 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000376 } else if (*gestureModeString != "default") {
377 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
Harry Cuttsf13161a2023-03-08 14:15:49 +0000385 mParameters.orientationAware =
386 config.getBool("touch.orientationAware")
387 .value_or(mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700388
Michael Wrighta9cf4192022-12-01 23:46:39 +0000389 mParameters.orientation = ui::ROTATION_0;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000390 std::optional<std::string> orientationString = config.getString("touch.orientation");
391 if (orientationString.has_value()) {
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700392 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
393 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
Harry Cuttsf13161a2023-03-08 14:15:49 +0000394 } else if (*orientationString == "ORIENTATION_90") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000395 mParameters.orientation = ui::ROTATION_90;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000396 } else if (*orientationString == "ORIENTATION_180") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000397 mParameters.orientation = ui::ROTATION_180;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000398 } else if (*orientationString == "ORIENTATION_270") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000399 mParameters.orientation = ui::ROTATION_270;
Harry Cuttsf13161a2023-03-08 14:15:49 +0000400 } else if (*orientationString != "ORIENTATION_0") {
401 ALOGW("Invalid value for touch.orientation: '%s'", orientationString->c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700402 }
403 }
404
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700405 mParameters.hasAssociatedDisplay = false;
406 mParameters.associatedDisplayIsExternal = false;
407 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100408 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000409 mParameters.deviceType == Parameters::DeviceType::POINTER ||
410 (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
411 getDeviceContext().getAssociatedViewport())) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700412 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100413 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800414 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Harry Cuttsf13161a2023-03-08 14:15:49 +0000415 mParameters.uniqueDisplayId = config.getString("touch.displayId").value_or("").c_str();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700416 }
417 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800418 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700419 mParameters.hasAssociatedDisplay = true;
420 }
421
422 // Initial downs on external touch devices should wake the device.
423 // Normally we don't do this for internal touch screens to prevent them from waking
424 // up in your pocket but you can enable it using the input device configuration.
Harry Cuttsf13161a2023-03-08 14:15:49 +0000425 mParameters.wake = config.getBool("touch.wake").value_or(getDeviceContext().isExternal());
Prabir Pradhan167c2702022-09-14 00:37:24 +0000426
Harry Cuttsf13161a2023-03-08 14:15:49 +0000427 std::optional<int32_t> usiVersionMajor = config.getInt("touch.usiVersionMajor");
428 std::optional<int32_t> usiVersionMinor = config.getInt("touch.usiVersionMinor");
429 if (usiVersionMajor.has_value() && usiVersionMinor.has_value()) {
430 mParameters.usiVersion = {
431 .majorVersion = *usiVersionMajor,
432 .minorVersion = *usiVersionMinor,
433 };
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000434 }
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700435
Harry Cuttsf13161a2023-03-08 14:15:49 +0000436 mParameters.enableForInactiveViewport =
437 config.getBool("touch.enableForInactiveViewport").value_or(false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700438}
439
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000440void TouchInputMapper::configureDeviceType() {
441 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
442 // The device is a touch screen.
443 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
444 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
445 // The device is a pointing device like a track pad.
446 mParameters.deviceType = Parameters::DeviceType::POINTER;
447 } else {
448 // The device is a touch pad of unknown purpose.
449 mParameters.deviceType = Parameters::DeviceType::POINTER;
450 }
451
452 // Type association takes precedence over the device type found in the idc file.
453 std::string deviceTypeString = getDeviceContext().getDeviceTypeAssociation().value_or("");
454 if (deviceTypeString.empty()) {
Harry Cuttsf13161a2023-03-08 14:15:49 +0000455 deviceTypeString =
456 getDeviceContext().getConfiguration().getString("touch.deviceType").value_or("");
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000457 }
458 if (deviceTypeString == "touchScreen") {
459 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
460 } else if (deviceTypeString == "touchNavigation") {
461 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
462 } else if (deviceTypeString == "pointer") {
463 mParameters.deviceType = Parameters::DeviceType::POINTER;
464 } else if (deviceTypeString != "default" && deviceTypeString != "") {
465 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
466 }
467}
468
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700469void TouchInputMapper::dumpParameters(std::string& dump) {
470 dump += INDENT3 "Parameters:\n";
471
Dominik Laskowski75788452021-02-09 18:51:25 -0800472 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700473
Dominik Laskowski75788452021-02-09 18:51:25 -0800474 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700475
476 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
477 "displayId='%s'\n",
478 toString(mParameters.hasAssociatedDisplay),
479 toString(mParameters.associatedDisplayIsExternal),
480 mParameters.uniqueDisplayId.c_str());
481 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800482 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000483 dump += StringPrintf(INDENT4 "UsiVersion: %s\n",
484 toString(mParameters.usiVersion, toString).c_str());
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700485 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
486 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700487}
488
489void TouchInputMapper::configureRawPointerAxes() {
490 mRawPointerAxes.clear();
491}
492
493void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
494 dump += INDENT3 "Raw Touch Axes:\n";
495 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
496 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
497 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
498 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
499 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
500 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
501 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
502 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
503 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
504 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
505 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
506 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
507 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
508}
509
510bool TouchInputMapper::hasExternalStylus() const {
511 return mExternalStylusConnected;
512}
513
514/**
515 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000516 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800517 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000518 * 3. Get the matching viewport by either unique id in idc file or by the display type
519 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800520 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700521 */
522std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800523 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000524 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800525 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700526 }
527
Christine Franks2a2293c2022-01-18 11:51:16 -0800528 const std::optional<std::string> associatedDisplayUniqueId =
529 getDeviceContext().getAssociatedDisplayUniqueId();
530 if (associatedDisplayUniqueId) {
531 return getDeviceContext().getAssociatedViewport();
532 }
533
Michael Wright227c5542020-07-02 18:30:52 +0100534 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800535 std::optional<DisplayViewport> viewport =
536 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
537 if (viewport) {
538 return viewport;
539 } else {
540 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
541 mConfig.defaultPointerDisplayId);
542 }
543 }
544
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700545 // Check if uniqueDisplayId is specified in idc file.
546 if (!mParameters.uniqueDisplayId.empty()) {
547 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
548 }
549
550 ViewportType viewportTypeToUse;
551 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100552 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700553 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100554 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700555 }
556
557 std::optional<DisplayViewport> viewport =
558 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100559 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700560 ALOGW("Input device %s should be associated with external display, "
561 "fallback to internal one for the external viewport is not found.",
562 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100563 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700564 }
565
566 return viewport;
567 }
568
569 // No associated display, return a non-display viewport.
570 DisplayViewport newViewport;
571 // Raw width and height in the natural orientation.
572 int32_t rawWidth = mRawPointerAxes.getRawWidth();
573 int32_t rawHeight = mRawPointerAxes.getRawHeight();
574 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
575 return std::make_optional(newViewport);
576}
577
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800578int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
579 if (resolution < 0) {
580 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
581 getDeviceName().c_str());
582 return 0;
583 }
584 return resolution;
585}
586
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800587void TouchInputMapper::initializeSizeRanges() {
588 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
589 mSizeScale = 0.0f;
590 return;
591 }
592
593 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000594 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800595
596 // Size factors.
597 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
598 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
599 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
600 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
601 } else {
602 mSizeScale = 0.0f;
603 }
604
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700605 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
606 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
607 .source = mSource,
608 .min = 0,
609 .max = diagonalSize,
610 .flat = 0,
611 .fuzz = 0,
612 .resolution = 0,
613 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800614
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800615 if (mRawPointerAxes.touchMajor.valid) {
616 mRawPointerAxes.touchMajor.resolution =
617 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700618 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800619 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800620
621 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700622 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800623 if (mRawPointerAxes.touchMinor.valid) {
624 mRawPointerAxes.touchMinor.resolution =
625 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700626 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800627 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800628
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700629 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
630 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
631 .source = mSource,
632 .min = 0,
633 .max = diagonalSize,
634 .flat = 0,
635 .fuzz = 0,
636 .resolution = 0,
637 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800638 if (mRawPointerAxes.toolMajor.valid) {
639 mRawPointerAxes.toolMajor.resolution =
640 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700641 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800642 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800643
644 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700645 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800646 if (mRawPointerAxes.toolMinor.valid) {
647 mRawPointerAxes.toolMinor.resolution =
648 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700649 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800650 }
651
652 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700653 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
654 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
655 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
656 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800657 } else {
658 // Support for other calibrations can be added here.
659 ALOGW("%s calibration is not supported for size ranges at the moment. "
660 "Using raw resolution instead",
661 ftl::enum_string(mCalibration.sizeCalibration).c_str());
662 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800663
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700664 mOrientedRanges.size = InputDeviceInfo::MotionRange{
665 .axis = AMOTION_EVENT_AXIS_SIZE,
666 .source = mSource,
667 .min = 0,
668 .max = 1.0,
669 .flat = 0,
670 .fuzz = 0,
671 .resolution = 0,
672 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800673}
674
675void TouchInputMapper::initializeOrientedRanges() {
676 // Configure X and Y factors.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000677 const float orientedScaleX = mRawToDisplay.getScaleX();
678 const float orientedScaleY = mRawToDisplay.getScaleY();
679 mOrientedXPrecision = 1.0f / orientedScaleX;
680 mOrientedYPrecision = 1.0f / orientedScaleY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800681
682 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
683 mOrientedRanges.x.source = mSource;
684 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
685 mOrientedRanges.y.source = mSource;
686
687 // Scale factor for terms that are not oriented in a particular axis.
688 // If the pixels are square then xScale == yScale otherwise we fake it
689 // by choosing an average.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000690 mGeometricScale = avg(orientedScaleX, orientedScaleY);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800691
692 initializeSizeRanges();
693
694 // Pressure factors.
695 mPressureScale = 0;
696 float pressureMax = 1.0;
697 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
698 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700699 if (mCalibration.pressureScale) {
700 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800701 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
702 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
703 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
704 }
705 }
706
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700707 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
708 .axis = AMOTION_EVENT_AXIS_PRESSURE,
709 .source = mSource,
710 .min = 0,
711 .max = pressureMax,
712 .flat = 0,
713 .fuzz = 0,
714 .resolution = 0,
715 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800716
717 // Tilt
718 mTiltXCenter = 0;
719 mTiltXScale = 0;
720 mTiltYCenter = 0;
721 mTiltYScale = 0;
722 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
723 if (mHaveTilt) {
724 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
725 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
726 mTiltXScale = M_PI / 180;
727 mTiltYScale = M_PI / 180;
728
729 if (mRawPointerAxes.tiltX.resolution) {
730 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
731 }
732 if (mRawPointerAxes.tiltY.resolution) {
733 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
734 }
735
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700736 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
737 .axis = AMOTION_EVENT_AXIS_TILT,
738 .source = mSource,
739 .min = 0,
740 .max = M_PI_2,
741 .flat = 0,
742 .fuzz = 0,
743 .resolution = 0,
744 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800745 }
746
747 // Orientation
748 mOrientationScale = 0;
749 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700750 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
751 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
752 .source = mSource,
753 .min = -M_PI,
754 .max = M_PI,
755 .flat = 0,
756 .fuzz = 0,
757 .resolution = 0,
758 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800759
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800760 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
761 if (mCalibration.orientationCalibration ==
762 Calibration::OrientationCalibration::INTERPOLATED) {
763 if (mRawPointerAxes.orientation.valid) {
764 if (mRawPointerAxes.orientation.maxValue > 0) {
765 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
766 } else if (mRawPointerAxes.orientation.minValue < 0) {
767 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
768 } else {
769 mOrientationScale = 0;
770 }
771 }
772 }
773
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700774 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
775 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
776 .source = mSource,
777 .min = -M_PI_2,
778 .max = M_PI_2,
779 .flat = 0,
780 .fuzz = 0,
781 .resolution = 0,
782 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800783 }
784
785 // Distance
786 mDistanceScale = 0;
787 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
788 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700789 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800790 }
791
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700792 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800793
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700794 .axis = AMOTION_EVENT_AXIS_DISTANCE,
795 .source = mSource,
796 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
797 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
798 .flat = 0,
799 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
800 .resolution = 0,
801 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800802 }
803
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000804 // Oriented X/Y range (in the rotated display's orientation)
805 const FloatRect rawFrame = Rect{mRawPointerAxes.x.minValue, mRawPointerAxes.y.minValue,
806 mRawPointerAxes.x.maxValue, mRawPointerAxes.y.maxValue}
807 .toFloatRect();
808 const auto orientedRangeRect = mRawToRotatedDisplay.transform(rawFrame);
809 mOrientedRanges.x.min = orientedRangeRect.left;
810 mOrientedRanges.y.min = orientedRangeRect.top;
811 mOrientedRanges.x.max = orientedRangeRect.right;
812 mOrientedRanges.y.max = orientedRangeRect.bottom;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800813
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000814 // Oriented flat (in the rotated display's orientation)
815 const auto orientedFlat =
816 transformWithoutTranslation(mRawToRotatedDisplay,
817 {static_cast<float>(mRawPointerAxes.x.flat),
818 static_cast<float>(mRawPointerAxes.y.flat)});
819 mOrientedRanges.x.flat = std::abs(orientedFlat.x);
820 mOrientedRanges.y.flat = std::abs(orientedFlat.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800821
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000822 // Oriented fuzz (in the rotated display's orientation)
823 const auto orientedFuzz =
824 transformWithoutTranslation(mRawToRotatedDisplay,
825 {static_cast<float>(mRawPointerAxes.x.fuzz),
826 static_cast<float>(mRawPointerAxes.y.fuzz)});
827 mOrientedRanges.x.fuzz = std::abs(orientedFuzz.x);
828 mOrientedRanges.y.fuzz = std::abs(orientedFuzz.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800829
Prabir Pradhan46211fb2022-12-17 00:30:39 +0000830 // Oriented resolution (in the rotated display's orientation)
831 const auto orientedRes =
832 transformWithoutTranslation(mRawToRotatedDisplay,
833 {static_cast<float>(mRawPointerAxes.x.resolution),
834 static_cast<float>(mRawPointerAxes.y.resolution)});
835 mOrientedRanges.x.resolution = std::abs(orientedRes.x);
836 mOrientedRanges.y.resolution = std::abs(orientedRes.y);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800837}
838
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000839void TouchInputMapper::computeInputTransforms() {
Prabir Pradhan3e798762022-12-02 21:02:11 +0000840 constexpr auto isRotated = [](const ui::Transform::RotationFlags& rotation) {
841 return rotation == ui::Transform::ROT_90 || rotation == ui::Transform::ROT_270;
842 };
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000843
Prabir Pradhan3e798762022-12-02 21:02:11 +0000844 // See notes about input coordinates in the inputflinger docs:
845 // //frameworks/native/services/inputflinger/docs/input_coordinates.md
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000846
847 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
Prabir Pradhan3e798762022-12-02 21:02:11 +0000848 ui::Transform undoOffsetInRaw;
849 undoOffsetInRaw.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000850
Prabir Pradhan3e798762022-12-02 21:02:11 +0000851 // Step 2: Rotate the raw coordinates to account for input device orientation. The coordinates
852 // will now be in the same orientation as the display in ROTATION_0.
853 // Note: Negating an ui::Rotation value will give its inverse rotation.
854 const auto inputDeviceOrientation = ui::Transform::toRotationFlags(-mParameters.orientation);
855 const ui::Size orientedRawSize = isRotated(inputDeviceOrientation)
856 ? ui::Size{mRawPointerAxes.getRawHeight(), mRawPointerAxes.getRawWidth()}
857 : ui::Size{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
858 // When rotating raw values, account for the extra unit added when calculating the raw range.
859 const auto orientInRaw = ui::Transform(inputDeviceOrientation, orientedRawSize.width - 1,
860 orientedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000861
Prabir Pradhan3e798762022-12-02 21:02:11 +0000862 // Step 3: Rotate the raw coordinates to account for the display rotation. The coordinates will
863 // now be in the same orientation as the rotated display. There is no need to rotate the
864 // coordinates to the display rotation if the device is not orientation-aware.
865 const auto viewportRotation = ui::Transform::toRotationFlags(-mViewport.orientation);
866 const auto rotatedRawSize = mParameters.orientationAware && isRotated(viewportRotation)
867 ? ui::Size{orientedRawSize.height, orientedRawSize.width}
868 : orientedRawSize;
869 // When rotating raw values, account for the extra unit added when calculating the raw range.
870 const auto rotateInRaw = mParameters.orientationAware
871 ? ui::Transform(viewportRotation, rotatedRawSize.width - 1, rotatedRawSize.height - 1)
872 : ui::Transform();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000873
Prabir Pradhan3e798762022-12-02 21:02:11 +0000874 // Step 4: Scale the raw coordinates to the display space.
875 // - Here, we assume that the raw surface of the touch device maps perfectly to the surface
876 // of the display panel. This is usually true for touchscreens.
877 // - From this point onward, we are no longer in the discrete space of the raw coordinates but
878 // are in the continuous space of the logical display.
879 ui::Transform scaleRawToDisplay;
880 const float xScale = static_cast<float>(mViewport.deviceWidth) / rotatedRawSize.width;
881 const float yScale = static_cast<float>(mViewport.deviceHeight) / rotatedRawSize.height;
882 scaleRawToDisplay.set(xScale, 0, 0, yScale);
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000883
Prabir Pradhan3e798762022-12-02 21:02:11 +0000884 // Step 5: Undo the display rotation to bring us back to the un-rotated display coordinate space
885 // that InputReader uses.
886 const auto undoRotateInDisplay =
887 ui::Transform(viewportRotation, mViewport.deviceWidth, mViewport.deviceHeight)
888 .inverse();
889
890 // Now put it all together!
891 mRawToRotatedDisplay = (scaleRawToDisplay * (rotateInRaw * (orientInRaw * undoOffsetInRaw)));
892 mRawToDisplay = (undoRotateInDisplay * mRawToRotatedDisplay);
893 mRawRotation = ui::Transform{mRawToDisplay.getOrientation()};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000894}
895
Prabir Pradhan1728b212021-10-19 16:00:03 -0700896void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000897 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700898
899 resolveExternalStylusPresence();
900
901 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100902 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000903 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700904 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100905 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700906 if (hasStylus()) {
907 mSource |= AINPUT_SOURCE_STYLUS;
908 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800909 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700910 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100911 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700912 if (hasStylus()) {
913 mSource |= AINPUT_SOURCE_STYLUS;
914 }
915 if (hasExternalStylus()) {
916 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
917 }
Michael Wright227c5542020-07-02 18:30:52 +0100918 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700919 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100920 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700921 } else {
922 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100923 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700924 }
925
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000926 const std::optional<DisplayViewport> newViewportOpt = findViewport();
927
928 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700929 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
930 ALOGW("Touch device '%s' did not report support for X or Y axis! "
931 "The device will be inoperable.",
932 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100933 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000934 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700935 ALOGI("Touch device '%s' could not query the properties of its associated "
936 "display. The device will be inoperable until the display size "
937 "becomes available.",
938 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100939 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700940 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000941 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
942 getDeviceName().c_str(), getDeviceId());
943 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000944 }
945
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700946 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000947 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000948 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
949 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
950 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
951 const float rawMeanResolution =
952 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700953
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000954 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
955 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700956 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700957 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000958 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
959 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
960 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700961
Michael Wright227c5542020-07-02 18:30:52 +0100962 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000963 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700964
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000965 mDisplayBounds = getNaturalDisplaySize(mViewport);
966 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
967 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700968
Prabir Pradhan3e798762022-12-02 21:02:11 +0000969 // TODO(b/257118693): Remove the dependence on the old orientation/rotation logic that
970 // uses mInputDeviceOrientation. The new logic uses the transforms calculated in
971 // computeInputTransforms().
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000972 // InputReader works in the un-rotated display coordinate space, so we don't need to do
973 // anything if the device is already orientation-aware. If the device is not
974 // orientation-aware, then we need to apply the inverse rotation of the display so that
975 // when the display rotation is applied later as a part of the per-window transform, we
976 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700977 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +0000978 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000979 : getInverseRotation(mViewport.orientation);
980 // For orientation-aware devices that work in the un-rotated coordinate space, the
981 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000982 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000983 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700984
985 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +0000986 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000987 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700988 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000989 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000990 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +0000991 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000992 mRawToDisplay.reset();
993 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000994 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700995 }
996 }
997
998 // If moving between pointer modes, need to reset some state.
999 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
1000 if (deviceModeChanged) {
1001 mOrientedRanges.clear();
1002 }
1003
Seunghwan Choi2de48e42023-01-17 20:45:15 +09001004 // Create and preserve the pointer controller in the following cases:
1005 const bool isPointerControllerNeeded =
1006 // - when the device is in pointer mode, to show the mouse cursor;
1007 (mDeviceMode == DeviceMode::POINTER) ||
1008 // - when pointer capture is enabled, to preserve the mouse cursor position;
1009 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
1010 mConfig.pointerCaptureRequest.enable) ||
1011 // - when we should be showing touches;
1012 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
1013 // - when we should be showing a pointer icon for direct styluses.
1014 (mDeviceMode == DeviceMode::DIRECT && mConfig.stylusPointerIconEnabled && hasStylus());
1015 if (isPointerControllerNeeded) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -08001016 if (mPointerController == nullptr) {
1017 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001018 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +00001019 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -08001020 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
1021 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001022 } else {
lilinnandef700b2022-06-17 19:32:01 +08001023 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
1024 !mConfig.showTouches) {
1025 mPointerController->clearSpots();
1026 }
Michael Wright17db18e2020-06-26 20:51:44 +01001027 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001028 }
1029
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001030 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001031 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001032 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001033 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001034 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001035
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001036 configureVirtualKeys();
1037
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001038 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001039
1040 // Location
1041 updateAffineTransformation();
1042
Michael Wright227c5542020-07-02 18:30:52 +01001043 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001044 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001045 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1046 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001047
1048 // Scale movements such that one whole swipe of the touch pad covers a
1049 // given area relative to the diagonal size of the display when no acceleration
1050 // is applied.
1051 // Assume that the touch pad has a square aspect ratio such that movements in
1052 // X and Y of the same number of raw units cover the same physical distance.
1053 mPointerXMovementScale =
1054 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1055 mPointerYMovementScale = mPointerXMovementScale;
1056
1057 // Scale zooms to cover a smaller range of the display than movements do.
1058 // This value determines the area around the pointer that is affected by freeform
1059 // pointer gestures.
1060 mPointerXZoomScale =
1061 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1062 mPointerYZoomScale = mPointerXZoomScale;
1063
HQ Liue6983c72022-04-19 22:14:56 +00001064 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1065 // axis is non positive value.
1066 const float minFreeformGestureWidth =
1067 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1068
1069 mPointerGestureMaxSwipeWidth =
1070 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1071 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001072 }
1073
1074 // Inform the dispatcher about the changes.
1075 *outResetNeeded = true;
1076 bumpGeneration();
1077 }
1078}
1079
Prabir Pradhan1728b212021-10-19 16:00:03 -07001080void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001081 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001082 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001083 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1084 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001085 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001086}
1087
1088void TouchInputMapper::configureVirtualKeys() {
1089 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001090 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001091
1092 mVirtualKeys.clear();
1093
1094 if (virtualKeyDefinitions.size() == 0) {
1095 return;
1096 }
1097
1098 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1099 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1100 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1101 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1102
1103 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1104 VirtualKey virtualKey;
1105
1106 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1107 int32_t keyCode;
1108 int32_t dummyKeyMetaState;
1109 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001110 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1111 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001112 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1113 continue; // drop the key
1114 }
1115
1116 virtualKey.keyCode = keyCode;
1117 virtualKey.flags = flags;
1118
1119 // convert the key definition's display coordinates into touch coordinates for a hit box
1120 int32_t halfWidth = virtualKeyDefinition.width / 2;
1121 int32_t halfHeight = virtualKeyDefinition.height / 2;
1122
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001123 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1124 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001125 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001126 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1127 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001128 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001129 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1130 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001131 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001132 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1133 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001134 touchScreenTop;
1135 mVirtualKeys.push_back(virtualKey);
1136 }
1137}
1138
1139void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1140 if (!mVirtualKeys.empty()) {
1141 dump += INDENT3 "Virtual Keys:\n";
1142
1143 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1144 const VirtualKey& virtualKey = mVirtualKeys[i];
1145 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1146 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1147 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1148 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1149 }
1150 }
1151}
1152
1153void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001154 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001155 Calibration& out = mCalibration;
1156
1157 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001158 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001159 std::optional<std::string> sizeCalibrationString = in.getString("touch.size.calibration");
1160 if (sizeCalibrationString.has_value()) {
1161 if (*sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001162 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001163 } else if (*sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001164 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001165 } else if (*sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001166 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001167 } else if (*sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001168 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001169 } else if (*sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001170 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001171 } else if (*sizeCalibrationString != "default") {
1172 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001173 }
1174 }
1175
Harry Cuttsf13161a2023-03-08 14:15:49 +00001176 out.sizeScale = in.getFloat("touch.size.scale");
1177 out.sizeBias = in.getFloat("touch.size.bias");
1178 out.sizeIsSummed = in.getBool("touch.size.isSummed");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001179
1180 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001181 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001182 std::optional<std::string> pressureCalibrationString =
1183 in.getString("touch.pressure.calibration");
1184 if (pressureCalibrationString.has_value()) {
1185 if (*pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001186 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001187 } else if (*pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001188 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001189 } else if (*pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001190 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001191 } else if (*pressureCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001192 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001193 pressureCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001194 }
1195 }
1196
Harry Cuttsf13161a2023-03-08 14:15:49 +00001197 out.pressureScale = in.getFloat("touch.pressure.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001198
1199 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001201 std::optional<std::string> orientationCalibrationString =
1202 in.getString("touch.orientation.calibration");
1203 if (orientationCalibrationString.has_value()) {
1204 if (*orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001205 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001206 } else if (*orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001207 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001208 } else if (*orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001209 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001210 } else if (*orientationCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001212 orientationCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001213 }
1214 }
1215
1216 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001217 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001218 std::optional<std::string> distanceCalibrationString =
1219 in.getString("touch.distance.calibration");
1220 if (distanceCalibrationString.has_value()) {
1221 if (*distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001222 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001223 } else if (*distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001224 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Harry Cuttsf13161a2023-03-08 14:15:49 +00001225 } else if (*distanceCalibrationString != "default") {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001226 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Harry Cuttsf13161a2023-03-08 14:15:49 +00001227 distanceCalibrationString->c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001228 }
1229 }
1230
Harry Cuttsf13161a2023-03-08 14:15:49 +00001231 out.distanceScale = in.getFloat("touch.distance.scale");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001232}
1233
1234void TouchInputMapper::resolveCalibration() {
1235 // Size
1236 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001237 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1238 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001239 }
1240 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001241 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001242 }
1243
1244 // Pressure
1245 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001246 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1247 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248 }
1249 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001250 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001251 }
1252
1253 // Orientation
1254 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001255 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1256 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001257 }
1258 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001259 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001260 }
1261
1262 // Distance
1263 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001264 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1265 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001266 }
1267 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001268 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001269 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001270}
1271
1272void TouchInputMapper::dumpCalibration(std::string& dump) {
1273 dump += INDENT3 "Calibration:\n";
1274
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001275 dump += INDENT4 "touch.size.calibration: ";
1276 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001277
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001278 if (mCalibration.sizeScale) {
1279 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001280 }
1281
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001282 if (mCalibration.sizeBias) {
1283 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284 }
1285
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001286 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001288 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001289 }
1290
1291 // Pressure
1292 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001293 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001294 dump += INDENT4 "touch.pressure.calibration: none\n";
1295 break;
Michael Wright227c5542020-07-02 18:30:52 +01001296 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001297 dump += INDENT4 "touch.pressure.calibration: physical\n";
1298 break;
Michael Wright227c5542020-07-02 18:30:52 +01001299 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001300 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1301 break;
1302 default:
1303 ALOG_ASSERT(false);
1304 }
1305
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001306 if (mCalibration.pressureScale) {
1307 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001308 }
1309
1310 // Orientation
1311 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001312 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001313 dump += INDENT4 "touch.orientation.calibration: none\n";
1314 break;
Michael Wright227c5542020-07-02 18:30:52 +01001315 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001316 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1317 break;
Michael Wright227c5542020-07-02 18:30:52 +01001318 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001319 dump += INDENT4 "touch.orientation.calibration: vector\n";
1320 break;
1321 default:
1322 ALOG_ASSERT(false);
1323 }
1324
1325 // Distance
1326 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001327 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001328 dump += INDENT4 "touch.distance.calibration: none\n";
1329 break;
Michael Wright227c5542020-07-02 18:30:52 +01001330 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001331 dump += INDENT4 "touch.distance.calibration: scaled\n";
1332 break;
1333 default:
1334 ALOG_ASSERT(false);
1335 }
1336
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001337 if (mCalibration.distanceScale) {
1338 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001339 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001340}
1341
1342void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1343 dump += INDENT3 "Affine Transformation:\n";
1344
1345 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1346 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1347 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1348 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1349 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1350 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1351}
1352
1353void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001354 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001355 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001356}
1357
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001358std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001359 std::list<NotifyArgs> out = cancelTouch(when, when);
1360 updateTouchSpots();
1361
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001362 mCursorButtonAccumulator.reset(getDeviceContext());
1363 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001364 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001365
1366 mPointerVelocityControl.reset();
1367 mWheelXVelocityControl.reset();
1368 mWheelYVelocityControl.reset();
1369
1370 mRawStatesPending.clear();
1371 mCurrentRawState.clear();
1372 mCurrentCookedState.clear();
1373 mLastRawState.clear();
1374 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001375 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001376 mSentHoverEnter = false;
1377 mHavePointerIds = false;
1378 mCurrentMotionAborted = false;
1379 mDownTime = 0;
1380
1381 mCurrentVirtualKey.down = false;
1382
1383 mPointerGesture.reset();
1384 mPointerSimple.reset();
1385 resetExternalStylus();
1386
1387 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001388 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001389 mPointerController->clearSpots();
1390 }
1391
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001392 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001393}
1394
1395void TouchInputMapper::resetExternalStylus() {
1396 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001397 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001398 mExternalStylusFusionTimeout = LLONG_MAX;
1399 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001400 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001401}
1402
1403void TouchInputMapper::clearStylusDataPendingFlags() {
1404 mExternalStylusDataPending = false;
1405 mExternalStylusFusionTimeout = LLONG_MAX;
1406}
1407
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001408std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001409 mCursorButtonAccumulator.process(rawEvent);
1410 mCursorScrollAccumulator.process(rawEvent);
1411 mTouchButtonAccumulator.process(rawEvent);
1412
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001413 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001414 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001415 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001416 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001417 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001418}
1419
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001420std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1421 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001422 if (mDeviceMode == DeviceMode::DISABLED) {
1423 // Only save the last pending state when the device is disabled.
1424 mRawStatesPending.clear();
1425 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001426 // Push a new state.
1427 mRawStatesPending.emplace_back();
1428
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001429 RawState& next = mRawStatesPending.back();
1430 next.clear();
1431 next.when = when;
1432 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001433
1434 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001435 next.buttonState = filterButtonState(mConfig,
1436 mTouchButtonAccumulator.getButtonState() |
1437 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001438
1439 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001440 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1441 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001442 mCursorScrollAccumulator.finishSync();
1443
1444 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001445 syncTouch(when, &next);
1446
1447 // The last RawState is the actually second to last, since we just added a new state
1448 const RawState& last =
1449 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001450
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001451 std::tie(next.when, next.readTime) =
1452 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1453 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001454
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001455 // Assign pointer ids.
1456 if (!mHavePointerIds) {
1457 assignPointerIds(last, next);
1458 }
1459
Prabir Pradhan011ca3d2023-02-22 21:31:39 +00001460 ALOGD_IF(debugRawEvents(),
Harry Cutts45483602022-08-24 14:36:48 +00001461 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1462 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1463 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1464 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1465 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1466 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001467
Arthur Hung9ad18942021-06-19 02:04:46 +00001468 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1469 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1470 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1471 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1472 next.rawPointerData.hoveringIdBits.value);
1473 }
1474
Harry Cutts33476232023-01-30 19:57:29 +00001475 out += processRawTouches(/*timeout=*/false);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001476 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001477}
1478
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001479std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1480 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001481 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001482 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001483 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001484 }
1485
1486 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1487 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1488 // touching the current state will only observe the events that have been dispatched to the
1489 // rest of the pipeline.
1490 const size_t N = mRawStatesPending.size();
1491 size_t count;
1492 for (count = 0; count < N; count++) {
1493 const RawState& next = mRawStatesPending[count];
1494
1495 // A failure to assign the stylus id means that we're waiting on stylus data
1496 // and so should defer the rest of the pipeline.
1497 if (assignExternalStylusId(next, timeout)) {
1498 break;
1499 }
1500
1501 // All ready to go.
1502 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001503 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001504 if (mCurrentRawState.when < mLastRawState.when) {
1505 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001506 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001507 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001508 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001509 }
1510 if (count != 0) {
1511 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1512 }
1513
1514 if (mExternalStylusDataPending) {
1515 if (timeout) {
1516 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1517 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001518 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001519 ALOGD_IF(DEBUG_STYLUS_FUSION,
1520 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001521 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001522 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001523 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1524 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1525 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1526 }
1527 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001528 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001529}
1530
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001531std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1532 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001533 // Always start with a clean state.
1534 mCurrentCookedState.clear();
1535
1536 // Apply stylus buttons to current raw state.
1537 applyExternalStylusButtonState(when);
1538
1539 // Handle policy on initial down or hover events.
1540 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1541 mCurrentRawState.rawPointerData.pointerCount != 0;
1542
1543 uint32_t policyFlags = 0;
1544 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1545 if (initialDown || buttonsPressed) {
1546 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001547 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001548 getContext()->fadePointer();
1549 }
1550
1551 if (mParameters.wake) {
1552 policyFlags |= POLICY_FLAG_WAKE;
1553 }
1554 }
1555
1556 // Consume raw off-screen touches before cooking pointer data.
1557 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001558 bool consumed;
1559 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1560 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001561 mCurrentRawState.rawPointerData.clear();
1562 }
1563
1564 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1565 // with cooked pointer data that has the same ids and indices as the raw data.
1566 // The following code can use either the raw or cooked data, as needed.
1567 cookPointerData();
1568
1569 // Apply stylus pressure to current cooked state.
1570 applyExternalStylusTouchState(when);
1571
1572 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001573 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1574 mSource, mViewport.displayId, policyFlags,
1575 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001576
1577 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001578 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001579 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1580 uint32_t id = idBits.clearFirstMarkedBit();
1581 const RawPointerData::Pointer& pointer =
1582 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001583 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001584 mCurrentCookedState.stylusIdBits.markBit(id);
1585 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1586 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1587 mCurrentCookedState.fingerIdBits.markBit(id);
1588 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1589 mCurrentCookedState.mouseIdBits.markBit(id);
1590 }
1591 }
1592 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1593 uint32_t id = idBits.clearFirstMarkedBit();
1594 const RawPointerData::Pointer& pointer =
1595 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001596 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001597 mCurrentCookedState.stylusIdBits.markBit(id);
1598 }
1599 }
1600
1601 // Stylus takes precedence over all tools, then mouse, then finger.
1602 PointerUsage pointerUsage = mPointerUsage;
1603 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1604 mCurrentCookedState.mouseIdBits.clear();
1605 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001606 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001607 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1608 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001609 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001610 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1611 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001612 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001613 }
1614
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001615 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001616 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001617 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001618 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001619 out += dispatchButtonRelease(when, readTime, policyFlags);
1620 out += dispatchHoverExit(when, readTime, policyFlags);
1621 out += dispatchTouches(when, readTime, policyFlags);
1622 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1623 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001624 }
1625
1626 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1627 mCurrentMotionAborted = false;
1628 }
1629 }
1630
1631 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001632 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1633 mSource, mViewport.displayId, policyFlags,
1634 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001635
1636 // Clear some transient state.
1637 mCurrentRawState.rawVScroll = 0;
1638 mCurrentRawState.rawHScroll = 0;
1639
1640 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001641 mLastRawState = mCurrentRawState;
1642 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001643 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001644}
1645
Garfield Tanc734e4f2021-01-15 20:01:39 -08001646void TouchInputMapper::updateTouchSpots() {
1647 if (!mConfig.showTouches || mPointerController == nullptr) {
1648 return;
1649 }
1650
1651 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1652 // clear touch spots.
1653 if (mDeviceMode != DeviceMode::DIRECT &&
1654 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1655 return;
1656 }
1657
1658 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1659 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1660
1661 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001662 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1663 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhanb3ce4532023-03-03 22:20:54 +00001664 mCurrentCookedState.cookedPointerData.touchingIdBits |
1665 mCurrentCookedState.cookedPointerData.hoveringIdBits,
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001666 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001667}
1668
1669bool TouchInputMapper::isTouchScreen() {
1670 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1671 mParameters.hasAssociatedDisplay;
1672}
1673
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001674void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001675 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1676 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001677 const int32_t pressedButtons =
1678 filterButtonState(mConfig,
1679 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001680 const int32_t releasedButtons =
1681 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1682
1683 mCurrentRawState.buttonState |= pressedButtons;
1684 mCurrentRawState.buttonState &= ~releasedButtons;
1685
1686 mExternalStylusButtonsApplied |= pressedButtons;
1687 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001688 }
1689}
1690
1691void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1692 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1693 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001694 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1695 return;
1696 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001697
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001698 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1699 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1700 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1701 : 0.f;
1702 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1703 pressure = *mExternalStylusState.pressure;
1704 }
1705 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1706 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001707
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001708 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001709 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001710 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001711 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001712 }
1713}
1714
1715bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001716 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001717 return false;
1718 }
1719
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001720 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001721 if (mFusedStylusPointerId &&
1722 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001723 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001724 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001725 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001726 }
1727
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001728 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1729 state.rawPointerData.pointerCount != 0;
1730 if (!initialDown) {
1731 return false;
1732 }
1733
1734 if (!mExternalStylusState.pressure) {
1735 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1736 return false;
1737 }
1738
1739 if (*mExternalStylusState.pressure != 0.0f) {
1740 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1741 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1742 return false;
1743 }
1744
1745 if (timeout) {
1746 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1747 mFusedStylusPointerId.reset();
1748 mExternalStylusFusionTimeout = LLONG_MAX;
1749 return false;
1750 }
1751
1752 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1753 // being processed until we either get pressure data or timeout.
1754 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1755 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1756 }
1757 ALOGD_IF(DEBUG_STYLUS_FUSION,
1758 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1759 mExternalStylusFusionTimeout);
1760 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1761 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001762}
1763
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001764std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1765 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001766 if (mDeviceMode == DeviceMode::POINTER) {
1767 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001768 // Since this is a synthetic event, we can consider its latency to be zero
1769 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001770 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001771 }
Michael Wright227c5542020-07-02 18:30:52 +01001772 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001773 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001774 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001775 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1776 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1777 }
1778 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001779 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001780}
1781
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001782std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1783 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001784 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001785 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001786 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001787 // The following three cases are handled here:
1788 // - We're in the middle of a fused stream of data;
1789 // - We're waiting on external stylus data before dispatching the initial down; or
1790 // - Only the button state, which is not reported through a specific pointer, has changed.
1791 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001792 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001793 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001794 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001795 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001796}
1797
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001798std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1799 uint32_t policyFlags, bool& outConsumed) {
1800 outConsumed = false;
1801 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001802 // Check for release of a virtual key.
1803 if (mCurrentVirtualKey.down) {
1804 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1805 // Pointer went up while virtual key was down.
1806 mCurrentVirtualKey.down = false;
1807 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001808 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1809 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1810 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001811 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1812 AKEY_EVENT_FLAG_FROM_SYSTEM |
1813 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001814 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001815 outConsumed = true;
1816 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001817 }
1818
1819 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1820 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1821 const RawPointerData::Pointer& pointer =
1822 mCurrentRawState.rawPointerData.pointerForId(id);
1823 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1824 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1825 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001826 outConsumed = true;
1827 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001828 }
1829 }
1830
1831 // Pointer left virtual key area or another pointer also went down.
1832 // Send key cancellation but do not consume the touch yet.
1833 // This is useful when the user swipes through from the virtual key area
1834 // into the main display surface.
1835 mCurrentVirtualKey.down = false;
1836 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001837 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1838 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001839 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1840 AKEY_EVENT_FLAG_FROM_SYSTEM |
1841 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1842 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001843 }
1844 }
1845
1846 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1847 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1848 // Pointer just went down. Check for virtual key press or off-screen touches.
1849 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1850 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001851 // Skip checking whether the pointer is inside the physical frame if the device is in
1852 // unscaled mode.
1853 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1854 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001855 // If exactly one pointer went down, check for virtual key hit.
1856 // Otherwise we will drop the entire stroke.
1857 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1858 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1859 if (virtualKey) {
1860 mCurrentVirtualKey.down = true;
1861 mCurrentVirtualKey.downTime = when;
1862 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1863 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1864 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001865 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1866 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001867
1868 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001869 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1870 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1871 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001872 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1873 AKEY_EVENT_ACTION_DOWN,
1874 AKEY_EVENT_FLAG_FROM_SYSTEM |
1875 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001876 }
1877 }
1878 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001879 outConsumed = true;
1880 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001881 }
1882 }
1883
1884 // Disable all virtual key touches that happen within a short time interval of the
1885 // most recent touch within the screen area. The idea is to filter out stray
1886 // virtual key presses when interacting with the touch screen.
1887 //
1888 // Problems we're trying to solve:
1889 //
1890 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1891 // virtual key area that is implemented by a separate touch panel and accidentally
1892 // triggers a virtual key.
1893 //
1894 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1895 // area and accidentally triggers a virtual key. This often happens when virtual keys
1896 // are layed out below the screen near to where the on screen keyboard's space bar
1897 // is displayed.
1898 if (mConfig.virtualKeyQuietTime > 0 &&
1899 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001900 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001901 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001902 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001903}
1904
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001905NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1906 uint32_t policyFlags, int32_t keyEventAction,
1907 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001908 int32_t keyCode = mCurrentVirtualKey.keyCode;
1909 int32_t scanCode = mCurrentVirtualKey.scanCode;
1910 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001911 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001912 policyFlags |= POLICY_FLAG_VIRTUAL;
1913
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001914 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1915 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1916 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001917}
1918
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001919std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1920 uint32_t policyFlags) {
1921 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001922 if (mCurrentMotionAborted) {
1923 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001924 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001925 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001926 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1927 if (!currentIdBits.isEmpty()) {
1928 int32_t metaState = getContext()->getGlobalMetaState();
1929 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001930 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001931 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1932 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001933 mCurrentCookedState.cookedPointerData.pointerProperties,
1934 mCurrentCookedState.cookedPointerData.pointerCoords,
1935 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1936 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1937 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001938 mCurrentMotionAborted = true;
1939 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001940 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001941}
1942
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001943// Updates pointer coords and properties for pointers with specified ids that have moved.
1944// Returns true if any of them changed.
1945static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1946 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1947 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1948 BitSet32 idBits) {
1949 bool changed = false;
1950 while (!idBits.isEmpty()) {
1951 uint32_t id = idBits.clearFirstMarkedBit();
1952 uint32_t inIndex = inIdToIndex[id];
1953 uint32_t outIndex = outIdToIndex[id];
1954
1955 const PointerProperties& curInProperties = inProperties[inIndex];
1956 const PointerCoords& curInCoords = inCoords[inIndex];
1957 PointerProperties& curOutProperties = outProperties[outIndex];
1958 PointerCoords& curOutCoords = outCoords[outIndex];
1959
1960 if (curInProperties != curOutProperties) {
1961 curOutProperties.copyFrom(curInProperties);
1962 changed = true;
1963 }
1964
1965 if (curInCoords != curOutCoords) {
1966 curOutCoords.copyFrom(curInCoords);
1967 changed = true;
1968 }
1969 }
1970 return changed;
1971}
1972
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001973std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1974 uint32_t policyFlags) {
1975 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001976 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1977 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1978 int32_t metaState = getContext()->getGlobalMetaState();
1979 int32_t buttonState = mCurrentCookedState.buttonState;
1980
1981 if (currentIdBits == lastIdBits) {
1982 if (!currentIdBits.isEmpty()) {
1983 // No pointer id changes so this is a move event.
1984 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001985 out.push_back(
1986 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1987 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1988 mCurrentCookedState.cookedPointerData.pointerProperties,
1989 mCurrentCookedState.cookedPointerData.pointerCoords,
1990 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1991 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1992 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001993 }
1994 } else {
1995 // There may be pointers going up and pointers going down and pointers moving
1996 // all at the same time.
1997 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1998 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1999 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
2000 BitSet32 dispatchedIdBits(lastIdBits.value);
2001
2002 // Update last coordinates of pointers that have moved so that we observe the new
2003 // pointer positions at the same time as other pointers that have just gone up.
2004 bool moveNeeded =
2005 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2006 mCurrentCookedState.cookedPointerData.pointerCoords,
2007 mCurrentCookedState.cookedPointerData.idToIndex,
2008 mLastCookedState.cookedPointerData.pointerProperties,
2009 mLastCookedState.cookedPointerData.pointerCoords,
2010 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2011 if (buttonState != mLastCookedState.buttonState) {
2012 moveNeeded = true;
2013 }
2014
2015 // Dispatch pointer up events.
2016 while (!upIdBits.isEmpty()) {
2017 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002018 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002019 if (isCanceled) {
2020 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2021 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002022 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2023 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2024 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2025 buttonState, 0,
2026 mLastCookedState.cookedPointerData.pointerProperties,
2027 mLastCookedState.cookedPointerData.pointerCoords,
2028 mLastCookedState.cookedPointerData.idToIndex,
2029 dispatchedIdBits, upId, mOrientedXPrecision,
2030 mOrientedYPrecision, mDownTime,
2031 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002032 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002033 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002034 }
2035
2036 // Dispatch move events if any of the remaining pointers moved from their old locations.
2037 // Although applications receive new locations as part of individual pointer up
2038 // events, they do not generally handle them except when presented in a move event.
2039 if (moveNeeded && !moveIdBits.isEmpty()) {
2040 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002041 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2042 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2043 mCurrentCookedState.cookedPointerData.pointerProperties,
2044 mCurrentCookedState.cookedPointerData.pointerCoords,
2045 mCurrentCookedState.cookedPointerData.idToIndex,
2046 dispatchedIdBits, -1, mOrientedXPrecision,
2047 mOrientedYPrecision, mDownTime,
2048 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002049 }
2050
2051 // Dispatch pointer down events using the new pointer locations.
2052 while (!downIdBits.isEmpty()) {
2053 uint32_t downId = downIdBits.clearFirstMarkedBit();
2054 dispatchedIdBits.markBit(downId);
2055
2056 if (dispatchedIdBits.count() == 1) {
2057 // First pointer is going down. Set down time.
2058 mDownTime = when;
2059 }
2060
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002061 out.push_back(
2062 dispatchMotion(when, readTime, policyFlags, mSource,
2063 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2064 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2065 mCurrentCookedState.cookedPointerData.pointerCoords,
2066 mCurrentCookedState.cookedPointerData.idToIndex,
2067 dispatchedIdBits, downId, mOrientedXPrecision,
2068 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002069 }
2070 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002071 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002072}
2073
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002074std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2075 uint32_t policyFlags) {
2076 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002077 if (mSentHoverEnter &&
2078 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2079 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2080 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002081 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2082 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2083 mLastCookedState.buttonState, 0,
2084 mLastCookedState.cookedPointerData.pointerProperties,
2085 mLastCookedState.cookedPointerData.pointerCoords,
2086 mLastCookedState.cookedPointerData.idToIndex,
2087 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2088 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2089 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002090 mSentHoverEnter = false;
2091 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002092 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002093}
2094
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002095std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2096 uint32_t policyFlags) {
2097 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002098 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2099 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2100 int32_t metaState = getContext()->getGlobalMetaState();
2101 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002102 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2103 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2104 mCurrentRawState.buttonState, 0,
2105 mCurrentCookedState.cookedPointerData.pointerProperties,
2106 mCurrentCookedState.cookedPointerData.pointerCoords,
2107 mCurrentCookedState.cookedPointerData.idToIndex,
2108 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2109 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2110 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002111 mSentHoverEnter = true;
2112 }
2113
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002114 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2115 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2116 mCurrentRawState.buttonState, 0,
2117 mCurrentCookedState.cookedPointerData.pointerProperties,
2118 mCurrentCookedState.cookedPointerData.pointerCoords,
2119 mCurrentCookedState.cookedPointerData.idToIndex,
2120 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2121 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2122 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002123 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002124 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002125}
2126
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002127std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2128 uint32_t policyFlags) {
2129 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002130 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2131 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2132 const int32_t metaState = getContext()->getGlobalMetaState();
2133 int32_t buttonState = mLastCookedState.buttonState;
2134 while (!releasedButtons.isEmpty()) {
2135 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2136 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002137 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2138 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2139 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002140 mLastCookedState.cookedPointerData.pointerProperties,
2141 mLastCookedState.cookedPointerData.pointerCoords,
2142 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002143 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2144 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002145 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002146 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002147}
2148
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002149std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2150 uint32_t policyFlags) {
2151 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002152 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2153 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2154 const int32_t metaState = getContext()->getGlobalMetaState();
2155 int32_t buttonState = mLastCookedState.buttonState;
2156 while (!pressedButtons.isEmpty()) {
2157 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2158 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002159 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2160 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2161 buttonState, 0,
2162 mCurrentCookedState.cookedPointerData.pointerProperties,
2163 mCurrentCookedState.cookedPointerData.pointerCoords,
2164 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2165 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2166 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002167 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002168 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002169}
2170
LiZhihong758eb562022-11-03 15:28:29 +08002171std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2172 uint32_t policyFlags,
2173 BitSet32 idBits,
2174 nsecs_t readTime) {
2175 std::list<NotifyArgs> out;
2176 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2177 const int32_t metaState = getContext()->getGlobalMetaState();
2178 int32_t buttonState = mLastCookedState.buttonState;
2179
2180 while (!releasedButtons.isEmpty()) {
2181 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2182 buttonState &= ~actionButton;
2183 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2184 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2185 metaState, buttonState, 0,
2186 mPointerGesture.lastGestureProperties,
2187 mPointerGesture.lastGestureCoords,
2188 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2189 mOrientedXPrecision, mOrientedYPrecision,
2190 mPointerGesture.downTime, MotionClassification::NONE));
2191 }
2192 return out;
2193}
2194
2195std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2196 uint32_t policyFlags,
2197 BitSet32 idBits,
2198 nsecs_t readTime) {
2199 std::list<NotifyArgs> out;
2200 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2201 const int32_t metaState = getContext()->getGlobalMetaState();
2202 int32_t buttonState = mLastCookedState.buttonState;
2203
2204 while (!pressedButtons.isEmpty()) {
2205 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2206 buttonState |= actionButton;
2207 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2208 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2209 buttonState, 0, mPointerGesture.currentGestureProperties,
2210 mPointerGesture.currentGestureCoords,
2211 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2212 mOrientedXPrecision, mOrientedYPrecision,
2213 mPointerGesture.downTime, MotionClassification::NONE));
2214 }
2215 return out;
2216}
2217
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002218const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2219 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2220 return cookedPointerData.touchingIdBits;
2221 }
2222 return cookedPointerData.hoveringIdBits;
2223}
2224
2225void TouchInputMapper::cookPointerData() {
2226 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2227
2228 mCurrentCookedState.cookedPointerData.clear();
2229 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2230 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2231 mCurrentRawState.rawPointerData.hoveringIdBits;
2232 mCurrentCookedState.cookedPointerData.touchingIdBits =
2233 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002234 mCurrentCookedState.cookedPointerData.canceledIdBits =
2235 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002236
2237 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2238 mCurrentCookedState.buttonState = 0;
2239 } else {
2240 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2241 }
2242
2243 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002244 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002245 for (uint32_t i = 0; i < currentPointerCount; i++) {
2246 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2247
2248 // Size
2249 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2250 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002251 case Calibration::SizeCalibration::GEOMETRIC:
2252 case Calibration::SizeCalibration::DIAMETER:
2253 case Calibration::SizeCalibration::BOX:
2254 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002255 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2256 touchMajor = in.touchMajor;
2257 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2258 toolMajor = in.toolMajor;
2259 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2260 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2261 : in.touchMajor;
2262 } else if (mRawPointerAxes.touchMajor.valid) {
2263 toolMajor = touchMajor = in.touchMajor;
2264 toolMinor = touchMinor =
2265 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2266 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2267 : in.touchMajor;
2268 } else if (mRawPointerAxes.toolMajor.valid) {
2269 touchMajor = toolMajor = in.toolMajor;
2270 touchMinor = toolMinor =
2271 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2272 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2273 : in.toolMajor;
2274 } else {
2275 ALOG_ASSERT(false,
2276 "No touch or tool axes. "
2277 "Size calibration should have been resolved to NONE.");
2278 touchMajor = 0;
2279 touchMinor = 0;
2280 toolMajor = 0;
2281 toolMinor = 0;
2282 size = 0;
2283 }
2284
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002285 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002286 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2287 if (touchingCount > 1) {
2288 touchMajor /= touchingCount;
2289 touchMinor /= touchingCount;
2290 toolMajor /= touchingCount;
2291 toolMinor /= touchingCount;
2292 size /= touchingCount;
2293 }
2294 }
2295
Michael Wright227c5542020-07-02 18:30:52 +01002296 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002297 touchMajor *= mGeometricScale;
2298 touchMinor *= mGeometricScale;
2299 toolMajor *= mGeometricScale;
2300 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002301 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002302 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2303 touchMinor = touchMajor;
2304 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2305 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002306 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002307 touchMinor = touchMajor;
2308 toolMinor = toolMajor;
2309 }
2310
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002311 mCalibration.applySizeScaleAndBias(touchMajor);
2312 mCalibration.applySizeScaleAndBias(touchMinor);
2313 mCalibration.applySizeScaleAndBias(toolMajor);
2314 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002315 size *= mSizeScale;
2316 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002317 case Calibration::SizeCalibration::DEFAULT:
2318 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2319 break;
2320 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002321 touchMajor = 0;
2322 touchMinor = 0;
2323 toolMajor = 0;
2324 toolMinor = 0;
2325 size = 0;
2326 break;
2327 }
2328
2329 // Pressure
2330 float pressure;
2331 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002332 case Calibration::PressureCalibration::PHYSICAL:
2333 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002334 pressure = in.pressure * mPressureScale;
2335 break;
2336 default:
2337 pressure = in.isHovering ? 0 : 1;
2338 break;
2339 }
2340
2341 // Tilt and Orientation
2342 float tilt;
2343 float orientation;
2344 if (mHaveTilt) {
2345 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2346 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002347 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002348 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2349 } else {
2350 tilt = 0;
2351
2352 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002353 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002354 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002355 break;
Michael Wright227c5542020-07-02 18:30:52 +01002356 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002357 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2358 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2359 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002360 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002361 float confidence = hypotf(c1, c2);
2362 float scale = 1.0f + confidence / 16.0f;
2363 touchMajor *= scale;
2364 touchMinor /= scale;
2365 toolMajor *= scale;
2366 toolMinor /= scale;
2367 } else {
2368 orientation = 0;
2369 }
2370 break;
2371 }
2372 default:
2373 orientation = 0;
2374 }
2375 }
2376
2377 // Distance
2378 float distance;
2379 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002380 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002381 distance = in.distance * mDistanceScale;
2382 break;
2383 default:
2384 distance = 0;
2385 }
2386
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002387 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2388 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002389 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2390 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002392 // Write output coords.
2393 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2394 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002395 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2396 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002397 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2398 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2399 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2400 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2401 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2402 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2403 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002404 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2405 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002406
Chris Ye364fdb52020-08-05 15:07:56 -07002407 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002408 uint32_t id = in.id;
2409 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2410 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2411 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002412 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2413 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002414 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2415 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2416 }
2417
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002418 // Write output properties.
2419 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002420 properties.clear();
2421 properties.id = id;
2422 properties.toolType = in.toolType;
2423
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002424 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002425 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002426 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002427 }
2428}
2429
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002430std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2431 uint32_t policyFlags,
2432 PointerUsage pointerUsage) {
2433 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002434 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002435 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002436 mPointerUsage = pointerUsage;
2437 }
2438
2439 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002440 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002441 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002442 break;
Michael Wright227c5542020-07-02 18:30:52 +01002443 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002444 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002445 break;
Michael Wright227c5542020-07-02 18:30:52 +01002446 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002447 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002448 break;
Michael Wright227c5542020-07-02 18:30:52 +01002449 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002450 break;
2451 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002452 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002453}
2454
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002455std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2456 uint32_t policyFlags) {
2457 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002458 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002459 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002460 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002461 break;
Michael Wright227c5542020-07-02 18:30:52 +01002462 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002463 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002464 break;
Michael Wright227c5542020-07-02 18:30:52 +01002465 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002466 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002467 break;
Michael Wright227c5542020-07-02 18:30:52 +01002468 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002469 break;
2470 }
2471
Michael Wright227c5542020-07-02 18:30:52 +01002472 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002473 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002474}
2475
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002476std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2477 uint32_t policyFlags,
2478 bool isTimeout) {
2479 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002480 // Update current gesture coordinates.
2481 bool cancelPreviousGesture, finishPreviousGesture;
2482 bool sendEvents =
2483 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2484 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002485 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002486 }
2487 if (finishPreviousGesture) {
2488 cancelPreviousGesture = false;
2489 }
2490
2491 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002492 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002493 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002494 if (finishPreviousGesture || cancelPreviousGesture) {
2495 mPointerController->clearSpots();
2496 }
2497
Michael Wright227c5542020-07-02 18:30:52 +01002498 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002499 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2500 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002501 mPointerGesture.currentGestureIdBits,
2502 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002503 }
2504 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002505 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002506 }
2507
2508 // Show or hide the pointer if needed.
2509 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002510 case PointerGesture::Mode::NEUTRAL:
2511 case PointerGesture::Mode::QUIET:
2512 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2513 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002514 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002515 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002516 }
2517 break;
Michael Wright227c5542020-07-02 18:30:52 +01002518 case PointerGesture::Mode::TAP:
2519 case PointerGesture::Mode::TAP_DRAG:
2520 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2521 case PointerGesture::Mode::HOVER:
2522 case PointerGesture::Mode::PRESS:
2523 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002524 // Unfade the pointer when the current gesture manipulates the
2525 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002526 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002527 break;
Michael Wright227c5542020-07-02 18:30:52 +01002528 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002529 // Fade the pointer when the current gesture manipulates a different
2530 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002531 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002532 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002533 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002534 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002535 }
2536 break;
2537 }
2538
2539 // Send events!
2540 int32_t metaState = getContext()->getGlobalMetaState();
2541 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002542 const MotionClassification classification =
2543 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2544 ? MotionClassification::TWO_FINGER_SWIPE
2545 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002546
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002547 uint32_t flags = 0;
2548
2549 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2550 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2551 }
2552
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002553 // Update last coordinates of pointers that have moved so that we observe the new
2554 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002555 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2556 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2557 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2558 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2559 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2560 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002561 bool moveNeeded = false;
2562 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2563 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2564 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2565 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2566 mPointerGesture.lastGestureIdBits.value);
2567 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2568 mPointerGesture.currentGestureCoords,
2569 mPointerGesture.currentGestureIdToIndex,
2570 mPointerGesture.lastGestureProperties,
2571 mPointerGesture.lastGestureCoords,
2572 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2573 if (buttonState != mLastCookedState.buttonState) {
2574 moveNeeded = true;
2575 }
2576 }
2577
2578 // Send motion events for all pointers that went up or were canceled.
2579 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2580 if (!dispatchedGestureIdBits.isEmpty()) {
2581 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002582 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002583 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002584 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002585 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2586 mPointerGesture.lastGestureProperties,
2587 mPointerGesture.lastGestureCoords,
2588 mPointerGesture.lastGestureIdToIndex,
2589 dispatchedGestureIdBits, -1, 0, 0,
2590 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002591
2592 dispatchedGestureIdBits.clear();
2593 } else {
2594 BitSet32 upGestureIdBits;
2595 if (finishPreviousGesture) {
2596 upGestureIdBits = dispatchedGestureIdBits;
2597 } else {
2598 upGestureIdBits.value =
2599 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2600 }
2601 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002602 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2603 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2604 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2605 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2606 readTime);
2607 }
2608 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002609 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2610 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2611 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2612 mPointerGesture.lastGestureProperties,
2613 mPointerGesture.lastGestureCoords,
2614 mPointerGesture.lastGestureIdToIndex,
2615 dispatchedGestureIdBits, id, 0, 0,
2616 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002617
2618 dispatchedGestureIdBits.clearBit(id);
2619 }
2620 }
2621 }
2622
2623 // Send motion events for all pointers that moved.
2624 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002625 out.push_back(
2626 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2627 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2628 mPointerGesture.currentGestureProperties,
2629 mPointerGesture.currentGestureCoords,
2630 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2631 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002632 }
2633
2634 // Send motion events for all pointers that went down.
2635 if (down) {
2636 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2637 ~dispatchedGestureIdBits.value);
2638 while (!downGestureIdBits.isEmpty()) {
2639 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2640 dispatchedGestureIdBits.markBit(id);
2641
2642 if (dispatchedGestureIdBits.count() == 1) {
2643 mPointerGesture.downTime = when;
2644 }
2645
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002646 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2647 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2648 buttonState, 0, mPointerGesture.currentGestureProperties,
2649 mPointerGesture.currentGestureCoords,
2650 mPointerGesture.currentGestureIdToIndex,
2651 dispatchedGestureIdBits, id, 0, 0,
2652 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002653 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2654 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2655 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2656 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2657 readTime);
2658 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002659 }
2660 }
2661
2662 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002663 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002664 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2665 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2666 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2667 mPointerGesture.currentGestureProperties,
2668 mPointerGesture.currentGestureCoords,
2669 mPointerGesture.currentGestureIdToIndex,
2670 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2671 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002672 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2673 // Synthesize a hover move event after all pointers go up to indicate that
2674 // the pointer is hovering again even if the user is not currently touching
2675 // the touch pad. This ensures that a view will receive a fresh hover enter
2676 // event after a tap.
Prabir Pradhan2719e822023-02-28 17:39:36 +00002677 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002678
2679 PointerProperties pointerProperties;
2680 pointerProperties.clear();
2681 pointerProperties.id = 0;
2682 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2683
2684 PointerCoords pointerCoords;
2685 pointerCoords.clear();
2686 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2687 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2688
2689 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002690 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2691 mSource, displayId, policyFlags,
2692 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2693 buttonState, MotionClassification::NONE,
2694 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2695 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2696 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002697 }
2698
2699 // Update state.
2700 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2701 if (!down) {
2702 mPointerGesture.lastGestureIdBits.clear();
2703 } else {
2704 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2705 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2706 uint32_t id = idBits.clearFirstMarkedBit();
2707 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2708 mPointerGesture.lastGestureProperties[index].copyFrom(
2709 mPointerGesture.currentGestureProperties[index]);
2710 mPointerGesture.lastGestureCoords[index].copyFrom(
2711 mPointerGesture.currentGestureCoords[index]);
2712 mPointerGesture.lastGestureIdToIndex[id] = index;
2713 }
2714 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002715 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002716}
2717
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002718std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2719 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002720 const MotionClassification classification =
2721 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2722 ? MotionClassification::TWO_FINGER_SWIPE
2723 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002724 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002725 // Cancel previously dispatches pointers.
2726 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2727 int32_t metaState = getContext()->getGlobalMetaState();
2728 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002729 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002730 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2731 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002732 mPointerGesture.lastGestureProperties,
2733 mPointerGesture.lastGestureCoords,
2734 mPointerGesture.lastGestureIdToIndex,
2735 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2736 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002737 }
2738
2739 // Reset the current pointer gesture.
2740 mPointerGesture.reset();
2741 mPointerVelocityControl.reset();
2742
2743 // Remove any current spots.
2744 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002745 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002746 mPointerController->clearSpots();
2747 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002748 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002749}
2750
2751bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2752 bool* outFinishPreviousGesture, bool isTimeout) {
2753 *outCancelPreviousGesture = false;
2754 *outFinishPreviousGesture = false;
2755
2756 // Handle TAP timeout.
2757 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002758 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002759
Michael Wright227c5542020-07-02 18:30:52 +01002760 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002761 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2762 // The tap/drag timeout has not yet expired.
2763 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2764 mConfig.pointerGestureTapDragInterval);
2765 } else {
2766 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002767 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002768 *outFinishPreviousGesture = true;
2769
2770 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002771 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002772 mPointerGesture.currentGestureIdBits.clear();
2773
2774 mPointerVelocityControl.reset();
2775 return true;
2776 }
2777 }
2778
2779 // We did not handle this timeout.
2780 return false;
2781 }
2782
2783 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2784 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2785
2786 // Update the velocity tracker.
2787 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002788 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002789 uint32_t id = idBits.clearFirstMarkedBit();
2790 const RawPointerData::Pointer& pointer =
2791 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002792 const float x = pointer.x * mPointerXMovementScale;
2793 const float y = pointer.y * mPointerYMovementScale;
2794 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2795 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002796 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002797 }
2798
2799 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2800 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002801 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2802 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2803 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002804 mPointerGesture.resetTap();
2805 }
2806
2807 // Pick a new active touch id if needed.
2808 // Choose an arbitrary pointer that just went down, if there is one.
2809 // Otherwise choose an arbitrary remaining pointer.
2810 // This guarantees we always have an active touch id when there is at least one pointer.
2811 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002812 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002813 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002814 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002815 mPointerGesture.firstTouchTime = when;
2816 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002817 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2818 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2819 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2820 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002821 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002822 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002823
2824 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002825 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002826 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002827 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2828 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2829 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002830 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002831 *outFinishPreviousGesture = true;
2832 }
2833
2834 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002835 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002836 mPointerGesture.currentGestureIdBits.clear();
2837
2838 mPointerVelocityControl.reset();
2839 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2840 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2841 // The pointer follows the active touch point.
2842 // Emit DOWN, MOVE, UP events at the pointer location.
2843 //
2844 // Only the active touch matters; other fingers are ignored. This policy helps
2845 // to handle the case where the user places a second finger on the touch pad
2846 // to apply the necessary force to depress an integrated button below the surface.
2847 // We don't want the second finger to be delivered to applications.
2848 //
2849 // For this to work well, we need to make sure to track the pointer that is really
2850 // active. If the user first puts one finger down to click then adds another
2851 // finger to drag then the active pointer should switch to the finger that is
2852 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002853 ALOGD_IF(DEBUG_GESTURES,
2854 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2855 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002856 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002857 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002858 *outFinishPreviousGesture = true;
2859 mPointerGesture.activeGestureId = 0;
2860 }
2861
2862 // Switch pointers if needed.
2863 // Find the fastest pointer and follow it.
2864 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002865 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002866 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002867 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002868 ALOGD_IF(DEBUG_GESTURES,
2869 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2870 "bestSpeed=%0.3f",
2871 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002872 }
2873 }
2874
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002875 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002876 // When using spots, the click will occur at the position of the anchor
2877 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002878 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002879 } else {
2880 mPointerVelocityControl.reset();
2881 }
2882
Prabir Pradhan2719e822023-02-28 17:39:36 +00002883 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002884
Michael Wright227c5542020-07-02 18:30:52 +01002885 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002886 mPointerGesture.currentGestureIdBits.clear();
2887 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2888 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2889 mPointerGesture.currentGestureProperties[0].clear();
2890 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2891 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2892 mPointerGesture.currentGestureCoords[0].clear();
2893 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2894 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2895 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2896 } else if (currentFingerCount == 0) {
2897 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002898 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002899 *outFinishPreviousGesture = true;
2900 }
2901
2902 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2903 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2904 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002905 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2906 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002907 lastFingerCount == 1) {
2908 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00002909 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002910 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2911 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002912 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002913
2914 mPointerGesture.tapUpTime = when;
2915 getContext()->requestTimeoutAtTime(when +
2916 mConfig.pointerGestureTapDragInterval);
2917
2918 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002919 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002920 mPointerGesture.currentGestureIdBits.clear();
2921 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2922 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2923 mPointerGesture.currentGestureProperties[0].clear();
2924 mPointerGesture.currentGestureProperties[0].id =
2925 mPointerGesture.activeGestureId;
2926 mPointerGesture.currentGestureProperties[0].toolType =
2927 AMOTION_EVENT_TOOL_TYPE_FINGER;
2928 mPointerGesture.currentGestureCoords[0].clear();
2929 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2930 mPointerGesture.tapX);
2931 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2932 mPointerGesture.tapY);
2933 mPointerGesture.currentGestureCoords[0]
2934 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2935
2936 tapped = true;
2937 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002938 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2939 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002940 }
2941 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002942 if (DEBUG_GESTURES) {
2943 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2944 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2945 (when - mPointerGesture.tapDownTime) * 0.000001f);
2946 } else {
2947 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2948 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002949 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002950 }
2951 }
2952
2953 mPointerVelocityControl.reset();
2954
2955 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002956 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002957 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002958 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002959 mPointerGesture.currentGestureIdBits.clear();
2960 }
2961 } else if (currentFingerCount == 1) {
2962 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2963 // The pointer follows the active touch point.
2964 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2965 // When in TAP_DRAG, emit MOVE events at the pointer location.
2966 ALOG_ASSERT(activeTouchId >= 0);
2967
Michael Wright227c5542020-07-02 18:30:52 +01002968 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2969 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002970 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00002971 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002972 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2973 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002974 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002975 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002976 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2977 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002978 }
2979 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002980 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2981 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002982 }
Michael Wright227c5542020-07-02 18:30:52 +01002983 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2984 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002985 }
2986
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002987 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002988 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002989 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002990 } else {
2991 mPointerVelocityControl.reset();
2992 }
2993
2994 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002995 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00002996 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002997 down = true;
2998 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002999 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003000 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003001 *outFinishPreviousGesture = true;
3002 }
3003 mPointerGesture.activeGestureId = 0;
3004 down = false;
3005 }
3006
Prabir Pradhan2719e822023-02-28 17:39:36 +00003007 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003008
3009 mPointerGesture.currentGestureIdBits.clear();
3010 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3011 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3012 mPointerGesture.currentGestureProperties[0].clear();
3013 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3014 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3015 mPointerGesture.currentGestureCoords[0].clear();
3016 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3017 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3018 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3019 down ? 1.0f : 0.0f);
3020
3021 if (lastFingerCount == 0 && currentFingerCount != 0) {
3022 mPointerGesture.resetTap();
3023 mPointerGesture.tapDownTime = when;
3024 mPointerGesture.tapX = x;
3025 mPointerGesture.tapY = y;
3026 }
3027 } else {
3028 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003029 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003030 }
3031
3032 mPointerController->setButtonState(mCurrentRawState.buttonState);
3033
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003034 if (DEBUG_GESTURES) {
3035 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3036 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3037 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3038 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3039 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3040 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3041 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3042 uint32_t id = idBits.clearFirstMarkedBit();
3043 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3044 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3045 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3046 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3047 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3048 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3049 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3050 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3051 }
3052 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3053 uint32_t id = idBits.clearFirstMarkedBit();
3054 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3055 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3056 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3057 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3058 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3059 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3060 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3061 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3062 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003063 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003064 return true;
3065}
3066
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003067bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3068 if (mPointerGesture.activeTouchId < 0) {
3069 mPointerGesture.resetQuietTime();
3070 return false;
3071 }
3072
3073 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3074 return true;
3075 }
3076
3077 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3078 bool isQuietTime = false;
3079 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3080 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3081 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3082 currentFingerCount < 2) {
3083 // Enter quiet time when exiting swipe or freeform state.
3084 // This is to prevent accidentally entering the hover state and flinging the
3085 // pointer when finishing a swipe and there is still one pointer left onscreen.
3086 isQuietTime = true;
3087 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3088 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3089 // Enter quiet time when releasing the button and there are still two or more
3090 // fingers down. This may indicate that one finger was used to press the button
3091 // but it has not gone up yet.
3092 isQuietTime = true;
3093 }
3094 if (isQuietTime) {
3095 mPointerGesture.quietTime = when;
3096 }
3097 return isQuietTime;
3098}
3099
3100std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3101 int32_t bestId = -1;
3102 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3103 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3104 uint32_t id = idBits.clearFirstMarkedBit();
3105 std::optional<float> vx =
3106 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3107 std::optional<float> vy =
3108 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3109 if (vx && vy) {
3110 float speed = hypotf(*vx, *vy);
3111 if (speed > bestSpeed) {
3112 bestId = id;
3113 bestSpeed = speed;
3114 }
3115 }
3116 }
3117 return std::make_pair(bestId, bestSpeed);
3118}
3119
3120void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3121 bool* finishPreviousGesture) {
3122 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3123 // to move before deciding what to do.
3124 //
3125 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3126 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3127 // just a press or long-press at the pointer location.
3128 //
3129 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3130 // pointer location.
3131 //
3132 // When the two fingers move enough or when additional fingers are added, we make a decision to
3133 // transition into SWIPE or FREEFORM mode accordingly.
3134 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3135 ALOG_ASSERT(activeTouchId >= 0);
3136
3137 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3138 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3139 bool settled =
3140 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3141 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3142 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3143 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3144 *finishPreviousGesture = true;
3145 } else if (!settled && currentFingerCount > lastFingerCount) {
3146 // Additional pointers have gone down but not yet settled.
3147 // Reset the gesture.
3148 ALOGD_IF(DEBUG_GESTURES,
3149 "Gestures: Resetting gesture since additional pointers went down for "
3150 "MULTITOUCH, settle time remaining %0.3fms",
3151 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3152 when) * 0.000001f);
3153 *cancelPreviousGesture = true;
3154 } else {
3155 // Continue previous gesture.
3156 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3157 }
3158
3159 if (*finishPreviousGesture || *cancelPreviousGesture) {
3160 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3161 mPointerGesture.activeGestureId = 0;
3162 mPointerGesture.referenceIdBits.clear();
3163 mPointerVelocityControl.reset();
3164
3165 // Use the centroid and pointer location as the reference points for the gesture.
3166 ALOGD_IF(DEBUG_GESTURES,
3167 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3168 "%0.3fms",
3169 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3170 when) * 0.000001f);
3171 mCurrentRawState.rawPointerData
3172 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3173 &mPointerGesture.referenceTouchY);
Prabir Pradhan2719e822023-02-28 17:39:36 +00003174 std::tie(mPointerGesture.referenceGestureX, mPointerGesture.referenceGestureY) =
3175 mPointerController->getPosition();
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003176 }
3177
3178 // Clear the reference deltas for fingers not yet included in the reference calculation.
3179 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3180 ~mPointerGesture.referenceIdBits.value);
3181 !idBits.isEmpty();) {
3182 uint32_t id = idBits.clearFirstMarkedBit();
3183 mPointerGesture.referenceDeltas[id].dx = 0;
3184 mPointerGesture.referenceDeltas[id].dy = 0;
3185 }
3186 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3187
3188 // Add delta for all fingers and calculate a common movement delta.
3189 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3190 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3191 mCurrentCookedState.fingerIdBits.value);
3192 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3193 bool first = (idBits == commonIdBits);
3194 uint32_t id = idBits.clearFirstMarkedBit();
3195 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3196 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3197 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3198 delta.dx += cpd.x - lpd.x;
3199 delta.dy += cpd.y - lpd.y;
3200
3201 if (first) {
3202 commonDeltaRawX = delta.dx;
3203 commonDeltaRawY = delta.dy;
3204 } else {
3205 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3206 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3207 }
3208 }
3209
3210 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3211 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3212 float dist[MAX_POINTER_ID + 1];
3213 int32_t distOverThreshold = 0;
3214 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3215 uint32_t id = idBits.clearFirstMarkedBit();
3216 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3217 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3218 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3219 distOverThreshold += 1;
3220 }
3221 }
3222
3223 // Only transition when at least two pointers have moved further than
3224 // the minimum distance threshold.
3225 if (distOverThreshold >= 2) {
3226 if (currentFingerCount > 2) {
3227 // There are more than two pointers, switch to FREEFORM.
3228 ALOGD_IF(DEBUG_GESTURES,
3229 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3230 currentFingerCount);
3231 *cancelPreviousGesture = true;
3232 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3233 } else {
3234 // There are exactly two pointers.
3235 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3236 uint32_t id1 = idBits.clearFirstMarkedBit();
3237 uint32_t id2 = idBits.firstMarkedBit();
3238 const RawPointerData::Pointer& p1 =
3239 mCurrentRawState.rawPointerData.pointerForId(id1);
3240 const RawPointerData::Pointer& p2 =
3241 mCurrentRawState.rawPointerData.pointerForId(id2);
3242 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3243 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3244 // There are two pointers but they are too far apart for a SWIPE,
3245 // switch to FREEFORM.
3246 ALOGD_IF(DEBUG_GESTURES,
3247 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3248 mutualDistance, mPointerGestureMaxSwipeWidth);
3249 *cancelPreviousGesture = true;
3250 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3251 } else {
3252 // There are two pointers. Wait for both pointers to start moving
3253 // before deciding whether this is a SWIPE or FREEFORM gesture.
3254 float dist1 = dist[id1];
3255 float dist2 = dist[id2];
3256 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3257 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3258 // Calculate the dot product of the displacement vectors.
3259 // When the vectors are oriented in approximately the same direction,
3260 // the angle betweeen them is near zero and the cosine of the angle
3261 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3262 // mag(v2).
3263 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3264 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3265 float dx1 = delta1.dx * mPointerXZoomScale;
3266 float dy1 = delta1.dy * mPointerYZoomScale;
3267 float dx2 = delta2.dx * mPointerXZoomScale;
3268 float dy2 = delta2.dy * mPointerYZoomScale;
3269 float dot = dx1 * dx2 + dy1 * dy2;
3270 float cosine = dot / (dist1 * dist2); // denominator always > 0
3271 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3272 // Pointers are moving in the same direction. Switch to SWIPE.
3273 ALOGD_IF(DEBUG_GESTURES,
3274 "Gestures: PRESS transitioned to SWIPE, "
3275 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3276 "cosine %0.3f >= %0.3f",
3277 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3278 mConfig.pointerGestureMultitouchMinDistance, cosine,
3279 mConfig.pointerGestureSwipeTransitionAngleCosine);
3280 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3281 } else {
3282 // Pointers are moving in different directions. Switch to FREEFORM.
3283 ALOGD_IF(DEBUG_GESTURES,
3284 "Gestures: PRESS transitioned to FREEFORM, "
3285 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3286 "cosine %0.3f < %0.3f",
3287 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3288 mConfig.pointerGestureMultitouchMinDistance, cosine,
3289 mConfig.pointerGestureSwipeTransitionAngleCosine);
3290 *cancelPreviousGesture = true;
3291 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3292 }
3293 }
3294 }
3295 }
3296 }
3297 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3298 // Switch from SWIPE to FREEFORM if additional pointers go down.
3299 // Cancel previous gesture.
3300 if (currentFingerCount > 2) {
3301 ALOGD_IF(DEBUG_GESTURES,
3302 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3303 currentFingerCount);
3304 *cancelPreviousGesture = true;
3305 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3306 }
3307 }
3308
3309 // Move the reference points based on the overall group motion of the fingers
3310 // except in PRESS mode while waiting for a transition to occur.
3311 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3312 (commonDeltaRawX || commonDeltaRawY)) {
3313 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3314 uint32_t id = idBits.clearFirstMarkedBit();
3315 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3316 delta.dx = 0;
3317 delta.dy = 0;
3318 }
3319
3320 mPointerGesture.referenceTouchX += commonDeltaRawX;
3321 mPointerGesture.referenceTouchY += commonDeltaRawY;
3322
3323 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3324 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3325
3326 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3327 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3328
3329 mPointerGesture.referenceGestureX += commonDeltaX;
3330 mPointerGesture.referenceGestureY += commonDeltaY;
3331 }
3332
3333 // Report gestures.
3334 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3335 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3336 // PRESS or SWIPE mode.
3337 ALOGD_IF(DEBUG_GESTURES,
3338 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3339 "currentTouchPointerCount=%d",
3340 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3341 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3342
3343 mPointerGesture.currentGestureIdBits.clear();
3344 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3345 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3346 mPointerGesture.currentGestureProperties[0].clear();
3347 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3348 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3349 mPointerGesture.currentGestureCoords[0].clear();
3350 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3351 mPointerGesture.referenceGestureX);
3352 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3353 mPointerGesture.referenceGestureY);
3354 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3355 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3356 float xOffset = static_cast<float>(commonDeltaRawX) /
3357 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3358 float yOffset = static_cast<float>(commonDeltaRawY) /
3359 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3360 mPointerGesture.currentGestureCoords[0]
3361 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3362 mPointerGesture.currentGestureCoords[0]
3363 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3364 }
3365 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3366 // FREEFORM mode.
3367 ALOGD_IF(DEBUG_GESTURES,
3368 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3369 "currentTouchPointerCount=%d",
3370 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3371 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3372
3373 mPointerGesture.currentGestureIdBits.clear();
3374
3375 BitSet32 mappedTouchIdBits;
3376 BitSet32 usedGestureIdBits;
3377 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3378 // Initially, assign the active gesture id to the active touch point
3379 // if there is one. No other touch id bits are mapped yet.
3380 if (!*cancelPreviousGesture) {
3381 mappedTouchIdBits.markBit(activeTouchId);
3382 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3383 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3384 mPointerGesture.activeGestureId;
3385 } else {
3386 mPointerGesture.activeGestureId = -1;
3387 }
3388 } else {
3389 // Otherwise, assume we mapped all touches from the previous frame.
3390 // Reuse all mappings that are still applicable.
3391 mappedTouchIdBits.value =
3392 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3393 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3394
3395 // Check whether we need to choose a new active gesture id because the
3396 // current went went up.
3397 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3398 ~mCurrentCookedState.fingerIdBits.value);
3399 !upTouchIdBits.isEmpty();) {
3400 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3401 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3402 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3403 mPointerGesture.activeGestureId = -1;
3404 break;
3405 }
3406 }
3407 }
3408
3409 ALOGD_IF(DEBUG_GESTURES,
3410 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3411 "activeGestureId=%d",
3412 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3413
3414 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3415 for (uint32_t i = 0; i < currentFingerCount; i++) {
3416 uint32_t touchId = idBits.clearFirstMarkedBit();
3417 uint32_t gestureId;
3418 if (!mappedTouchIdBits.hasBit(touchId)) {
3419 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3420 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3421 ALOGD_IF(DEBUG_GESTURES,
3422 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3423 gestureId);
3424 } else {
3425 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3426 ALOGD_IF(DEBUG_GESTURES,
3427 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3428 touchId, gestureId);
3429 }
3430 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3431 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3432
3433 const RawPointerData::Pointer& pointer =
3434 mCurrentRawState.rawPointerData.pointerForId(touchId);
3435 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3436 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3437 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3438
3439 mPointerGesture.currentGestureProperties[i].clear();
3440 mPointerGesture.currentGestureProperties[i].id = gestureId;
3441 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3442 mPointerGesture.currentGestureCoords[i].clear();
3443 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3444 mPointerGesture.referenceGestureX +
3445 deltaX);
3446 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3447 mPointerGesture.referenceGestureY +
3448 deltaY);
3449 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3450 }
3451
3452 if (mPointerGesture.activeGestureId < 0) {
3453 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3454 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3455 mPointerGesture.activeGestureId);
3456 }
3457 }
3458}
3459
Harry Cutts714d1ad2022-08-24 16:36:43 +00003460void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3461 const RawPointerData::Pointer& currentPointer =
3462 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3463 const RawPointerData::Pointer& lastPointer =
3464 mLastRawState.rawPointerData.pointerForId(pointerId);
3465 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3466 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3467
3468 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3469 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3470
3471 mPointerController->move(deltaX, deltaY);
3472}
3473
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003474std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3475 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003476 mPointerSimple.currentCoords.clear();
3477 mPointerSimple.currentProperties.clear();
3478
3479 bool down, hovering;
3480 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3481 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3482 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003483 mPointerController
3484 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3485 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003486
3487 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3488 down = !hovering;
3489
Prabir Pradhan2719e822023-02-28 17:39:36 +00003490 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003491 mPointerSimple.currentCoords.copyFrom(
3492 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3493 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3494 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3495 mPointerSimple.currentProperties.id = 0;
3496 mPointerSimple.currentProperties.toolType =
3497 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3498 } else {
3499 down = false;
3500 hovering = false;
3501 }
3502
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003503 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003504}
3505
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003506std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3507 uint32_t policyFlags) {
3508 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003509}
3510
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003511std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3512 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003513 mPointerSimple.currentCoords.clear();
3514 mPointerSimple.currentProperties.clear();
3515
3516 bool down, hovering;
3517 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3518 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003519 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003520 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003521 } else {
3522 mPointerVelocityControl.reset();
3523 }
3524
3525 down = isPointerDown(mCurrentRawState.buttonState);
3526 hovering = !down;
3527
Prabir Pradhan2719e822023-02-28 17:39:36 +00003528 const auto [x, y] = mPointerController->getPosition();
3529 const uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003530 mPointerSimple.currentCoords.copyFrom(
3531 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3532 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3533 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3534 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3535 hovering ? 0.0f : 1.0f);
3536 mPointerSimple.currentProperties.id = 0;
3537 mPointerSimple.currentProperties.toolType =
3538 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3539 } else {
3540 mPointerVelocityControl.reset();
3541
3542 down = false;
3543 hovering = false;
3544 }
3545
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003546 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003547}
3548
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003549std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3550 uint32_t policyFlags) {
3551 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003552
3553 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003554
3555 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003556}
3557
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003558std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3559 uint32_t policyFlags, bool down,
3560 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003561 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3562 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003563 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003564 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003565
3566 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003567 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003568 mPointerController->clearSpots();
3569 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003570 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003571 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003572 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003573 }
Garfield Tan9514d782020-11-10 16:37:23 -08003574 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003575
Prabir Pradhan2719e822023-02-28 17:39:36 +00003576 const auto [xCursorPosition, yCursorPosition] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003577
3578 if (mPointerSimple.down && !down) {
3579 mPointerSimple.down = false;
3580
3581 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003582 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3583 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3584 0, metaState, mLastRawState.buttonState,
3585 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3586 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3587 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3588 yCursorPosition, mPointerSimple.downTime,
3589 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003590 }
3591
3592 if (mPointerSimple.hovering && !hovering) {
3593 mPointerSimple.hovering = false;
3594
3595 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003596 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3597 mSource, displayId, policyFlags,
3598 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3599 mLastRawState.buttonState, MotionClassification::NONE,
3600 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3601 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3602 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3603 yCursorPosition, mPointerSimple.downTime,
3604 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003605 }
3606
3607 if (down) {
3608 if (!mPointerSimple.down) {
3609 mPointerSimple.down = true;
3610 mPointerSimple.downTime = when;
3611
3612 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003613 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3614 mSource, displayId, policyFlags,
3615 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3616 mCurrentRawState.buttonState, MotionClassification::NONE,
3617 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3618 &mPointerSimple.currentProperties,
3619 &mPointerSimple.currentCoords, mOrientedXPrecision,
3620 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3621 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003622 }
3623
3624 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003625 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3626 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3627 0, 0, metaState, mCurrentRawState.buttonState,
3628 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3629 &mPointerSimple.currentProperties,
3630 &mPointerSimple.currentCoords, mOrientedXPrecision,
3631 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3632 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003633 }
3634
3635 if (hovering) {
3636 if (!mPointerSimple.hovering) {
3637 mPointerSimple.hovering = true;
3638
3639 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003640 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3641 mSource, displayId, policyFlags,
3642 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3643 mCurrentRawState.buttonState, MotionClassification::NONE,
3644 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3645 &mPointerSimple.currentProperties,
3646 &mPointerSimple.currentCoords, mOrientedXPrecision,
3647 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3648 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003649 }
3650
3651 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003652 out.push_back(
3653 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3654 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3655 metaState, mCurrentRawState.buttonState,
3656 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3657 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3658 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3659 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003660 }
3661
3662 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3663 float vscroll = mCurrentRawState.rawVScroll;
3664 float hscroll = mCurrentRawState.rawHScroll;
3665 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3666 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3667
3668 // Send scroll.
3669 PointerCoords pointerCoords;
3670 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3671 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3672 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3673
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003674 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3675 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3676 0, 0, metaState, mCurrentRawState.buttonState,
3677 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3678 &mPointerSimple.currentProperties, &pointerCoords,
3679 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3680 yCursorPosition, mPointerSimple.downTime,
3681 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003682 }
3683
3684 // Save state.
3685 if (down || hovering) {
3686 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3687 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003688 mPointerSimple.displayId = displayId;
3689 mPointerSimple.source = mSource;
3690 mPointerSimple.lastCursorX = xCursorPosition;
3691 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003692 } else {
3693 mPointerSimple.reset();
3694 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003695 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003696}
3697
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003698std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3699 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003700 std::list<NotifyArgs> out;
3701 if (mPointerSimple.down || mPointerSimple.hovering) {
3702 int32_t metaState = getContext()->getGlobalMetaState();
3703 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3704 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3705 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3706 metaState, mLastRawState.buttonState,
3707 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3708 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3709 mOrientedXPrecision, mOrientedYPrecision,
3710 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3711 mPointerSimple.downTime,
3712 /* videoFrames */ {}));
3713 if (mPointerController != nullptr) {
3714 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3715 }
3716 }
3717 mPointerSimple.reset();
3718 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003719}
3720
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003721static bool isStylusEvent(uint32_t source, int32_t action, const PointerProperties* properties) {
3722 if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
3723 return false;
3724 }
3725 const auto actionIndex = action >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3726 return isStylusToolType(properties[actionIndex].toolType);
3727}
3728
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003729NotifyMotionArgs TouchInputMapper::dispatchMotion(
3730 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3731 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003732 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3733 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003734 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003735 PointerCoords pointerCoords[MAX_POINTERS];
3736 PointerProperties pointerProperties[MAX_POINTERS];
3737 uint32_t pointerCount = 0;
3738 while (!idBits.isEmpty()) {
3739 uint32_t id = idBits.clearFirstMarkedBit();
3740 uint32_t index = idToIndex[id];
3741 pointerProperties[pointerCount].copyFrom(properties[index]);
3742 pointerCoords[pointerCount].copyFrom(coords[index]);
3743
3744 if (changedId >= 0 && id == uint32_t(changedId)) {
3745 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3746 }
3747
3748 pointerCount += 1;
3749 }
3750
3751 ALOG_ASSERT(pointerCount != 0);
3752
3753 if (changedId >= 0 && pointerCount == 1) {
3754 // Replace initial down and final up action.
3755 // We can compare the action without masking off the changed pointer index
3756 // because we know the index is 0.
3757 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3758 action = AMOTION_EVENT_ACTION_DOWN;
3759 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003760 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3761 action = AMOTION_EVENT_ACTION_CANCEL;
3762 } else {
3763 action = AMOTION_EVENT_ACTION_UP;
3764 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003765 } else {
3766 // Can't happen.
3767 ALOG_ASSERT(false);
3768 }
3769 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003770
3771 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3772 const bool showDirectStylusPointer = mConfig.stylusPointerIconEnabled &&
3773 mDeviceMode == DeviceMode::DIRECT && isStylusEvent(source, action, pointerProperties) &&
Seunghwan Choi356026c2023-02-01 14:37:25 +09003774 mPointerController && displayId != ADISPLAY_ID_NONE &&
3775 displayId == mPointerController->getDisplayId();
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003776 if (showDirectStylusPointer) {
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003777 switch (action & AMOTION_EVENT_ACTION_MASK) {
3778 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3779 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3780 mPointerController->setPresentation(
Seunghwan Choi75789cd2023-01-13 20:31:59 +09003781 PointerControllerInterface::Presentation::STYLUS_HOVER);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003782 mPointerController
3783 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[0].getX(),
3784 mCurrentCookedState.cookedPointerData.pointerCoords[0]
3785 .getY());
3786 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3787 break;
3788 case AMOTION_EVENT_ACTION_HOVER_EXIT:
3789 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
3790 break;
3791 }
3792 }
3793
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003794 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3795 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003796 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003797 std::tie(xCursorPosition, yCursorPosition) = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003798 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003799 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003800 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003801 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003802 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003803 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3804 policyFlags, action, actionButton, flags, metaState, buttonState,
3805 classification, edgeFlags, pointerCount, pointerProperties,
3806 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3807 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003808}
3809
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003810std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3811 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003812 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3813 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003814 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003815}
3816
Prabir Pradhan1728b212021-10-19 16:00:03 -07003817bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003818 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003819 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003820 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003821}
3822
3823const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3824 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003825 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3826 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3827 "left=%d, top=%d, right=%d, bottom=%d",
3828 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3829 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003830
3831 if (virtualKey.isHit(x, y)) {
3832 return &virtualKey;
3833 }
3834 }
3835
3836 return nullptr;
3837}
3838
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003839void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3840 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3841 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003842
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003843 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003844
3845 if (currentPointerCount == 0) {
3846 // No pointers to assign.
3847 return;
3848 }
3849
3850 if (lastPointerCount == 0) {
3851 // All pointers are new.
3852 for (uint32_t i = 0; i < currentPointerCount; i++) {
3853 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003854 current.rawPointerData.pointers[i].id = id;
3855 current.rawPointerData.idToIndex[id] = i;
3856 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003857 }
3858 return;
3859 }
3860
3861 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003862 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003863 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003864 uint32_t id = last.rawPointerData.pointers[0].id;
3865 current.rawPointerData.pointers[0].id = id;
3866 current.rawPointerData.idToIndex[id] = 0;
3867 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003868 return;
3869 }
3870
3871 // General case.
3872 // We build a heap of squared euclidean distances between current and last pointers
3873 // associated with the current and last pointer indices. Then, we find the best
3874 // match (by distance) for each current pointer.
3875 // The pointers must have the same tool type but it is possible for them to
3876 // transition from hovering to touching or vice-versa while retaining the same id.
3877 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3878
3879 uint32_t heapSize = 0;
3880 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3881 currentPointerIndex++) {
3882 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3883 lastPointerIndex++) {
3884 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003885 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003886 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003887 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003888 if (currentPointer.toolType == lastPointer.toolType) {
3889 int64_t deltaX = currentPointer.x - lastPointer.x;
3890 int64_t deltaY = currentPointer.y - lastPointer.y;
3891
3892 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3893
3894 // Insert new element into the heap (sift up).
3895 heap[heapSize].currentPointerIndex = currentPointerIndex;
3896 heap[heapSize].lastPointerIndex = lastPointerIndex;
3897 heap[heapSize].distance = distance;
3898 heapSize += 1;
3899 }
3900 }
3901 }
3902
3903 // Heapify
3904 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3905 startIndex -= 1;
3906 for (uint32_t parentIndex = startIndex;;) {
3907 uint32_t childIndex = parentIndex * 2 + 1;
3908 if (childIndex >= heapSize) {
3909 break;
3910 }
3911
3912 if (childIndex + 1 < heapSize &&
3913 heap[childIndex + 1].distance < heap[childIndex].distance) {
3914 childIndex += 1;
3915 }
3916
3917 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3918 break;
3919 }
3920
3921 swap(heap[parentIndex], heap[childIndex]);
3922 parentIndex = childIndex;
3923 }
3924 }
3925
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003926 if (DEBUG_POINTER_ASSIGNMENT) {
3927 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3928 for (size_t i = 0; i < heapSize; i++) {
3929 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3930 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3931 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003932 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003933
3934 // Pull matches out by increasing order of distance.
3935 // To avoid reassigning pointers that have already been matched, the loop keeps track
3936 // of which last and current pointers have been matched using the matchedXXXBits variables.
3937 // It also tracks the used pointer id bits.
3938 BitSet32 matchedLastBits(0);
3939 BitSet32 matchedCurrentBits(0);
3940 BitSet32 usedIdBits(0);
3941 bool first = true;
3942 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3943 while (heapSize > 0) {
3944 if (first) {
3945 // The first time through the loop, we just consume the root element of
3946 // the heap (the one with smallest distance).
3947 first = false;
3948 } else {
3949 // Previous iterations consumed the root element of the heap.
3950 // Pop root element off of the heap (sift down).
3951 heap[0] = heap[heapSize];
3952 for (uint32_t parentIndex = 0;;) {
3953 uint32_t childIndex = parentIndex * 2 + 1;
3954 if (childIndex >= heapSize) {
3955 break;
3956 }
3957
3958 if (childIndex + 1 < heapSize &&
3959 heap[childIndex + 1].distance < heap[childIndex].distance) {
3960 childIndex += 1;
3961 }
3962
3963 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3964 break;
3965 }
3966
3967 swap(heap[parentIndex], heap[childIndex]);
3968 parentIndex = childIndex;
3969 }
3970
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003971 if (DEBUG_POINTER_ASSIGNMENT) {
3972 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3973 for (size_t j = 0; j < heapSize; j++) {
3974 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3975 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3976 heap[j].distance);
3977 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003978 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003979 }
3980
3981 heapSize -= 1;
3982
3983 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3984 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3985
3986 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3987 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3988
3989 matchedCurrentBits.markBit(currentPointerIndex);
3990 matchedLastBits.markBit(lastPointerIndex);
3991
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003992 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3993 current.rawPointerData.pointers[currentPointerIndex].id = id;
3994 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3995 current.rawPointerData.markIdBit(id,
3996 current.rawPointerData.isHovering(
3997 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003998 usedIdBits.markBit(id);
3999
Harry Cutts45483602022-08-24 14:36:48 +00004000 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4001 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4002 ", distance=%" PRIu64,
4003 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004004 break;
4005 }
4006 }
4007
4008 // Assign fresh ids to pointers that were not matched in the process.
4009 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4010 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4011 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4012
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004013 current.rawPointerData.pointers[currentPointerIndex].id = id;
4014 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4015 current.rawPointerData.markIdBit(id,
4016 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004017
Harry Cutts45483602022-08-24 14:36:48 +00004018 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4019 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4020 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004021 }
4022}
4023
4024int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4025 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4026 return AKEY_STATE_VIRTUAL;
4027 }
4028
4029 for (const VirtualKey& virtualKey : mVirtualKeys) {
4030 if (virtualKey.keyCode == keyCode) {
4031 return AKEY_STATE_UP;
4032 }
4033 }
4034
4035 return AKEY_STATE_UNKNOWN;
4036}
4037
4038int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4039 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4040 return AKEY_STATE_VIRTUAL;
4041 }
4042
4043 for (const VirtualKey& virtualKey : mVirtualKeys) {
4044 if (virtualKey.scanCode == scanCode) {
4045 return AKEY_STATE_UP;
4046 }
4047 }
4048
4049 return AKEY_STATE_UNKNOWN;
4050}
4051
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004052bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4053 const std::vector<int32_t>& keyCodes,
4054 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004055 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004056 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004057 if (virtualKey.keyCode == keyCodes[i]) {
4058 outFlags[i] = 1;
4059 }
4060 }
4061 }
4062
4063 return true;
4064}
4065
4066std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4067 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004068 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004069 return std::make_optional(mPointerController->getDisplayId());
4070 } else {
4071 return std::make_optional(mViewport.displayId);
4072 }
4073 }
4074 return std::nullopt;
4075}
4076
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004077} // namespace android