blob: df7ba49b4d35f95045a1743670903a72fba2c121 [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
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001661 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1662 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhanb3ce4532023-03-03 22:20:54 +00001663 mCurrentCookedState.cookedPointerData.touchingIdBits |
1664 mCurrentCookedState.cookedPointerData.hoveringIdBits,
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001665 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001666}
1667
1668bool TouchInputMapper::isTouchScreen() {
1669 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1670 mParameters.hasAssociatedDisplay;
1671}
1672
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001673void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001674 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1675 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001676 const int32_t pressedButtons =
1677 filterButtonState(mConfig,
1678 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001679 const int32_t releasedButtons =
1680 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1681
1682 mCurrentRawState.buttonState |= pressedButtons;
1683 mCurrentRawState.buttonState &= ~releasedButtons;
1684
1685 mExternalStylusButtonsApplied |= pressedButtons;
1686 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001687 }
1688}
1689
1690void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1691 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1692 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001693 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1694 return;
1695 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001696
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001697 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1698 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1699 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1700 : 0.f;
1701 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1702 pressure = *mExternalStylusState.pressure;
1703 }
1704 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1705 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001706
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001707 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001708 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001709 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001710 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001711 }
1712}
1713
1714bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001715 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001716 return false;
1717 }
1718
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001719 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001720 if (mFusedStylusPointerId &&
1721 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001722 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001723 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001724 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001725 }
1726
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001727 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1728 state.rawPointerData.pointerCount != 0;
1729 if (!initialDown) {
1730 return false;
1731 }
1732
1733 if (!mExternalStylusState.pressure) {
1734 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1735 return false;
1736 }
1737
1738 if (*mExternalStylusState.pressure != 0.0f) {
1739 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1740 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1741 return false;
1742 }
1743
1744 if (timeout) {
1745 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1746 mFusedStylusPointerId.reset();
1747 mExternalStylusFusionTimeout = LLONG_MAX;
1748 return false;
1749 }
1750
1751 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1752 // being processed until we either get pressure data or timeout.
1753 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1754 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1755 }
1756 ALOGD_IF(DEBUG_STYLUS_FUSION,
1757 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1758 mExternalStylusFusionTimeout);
1759 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1760 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001761}
1762
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001763std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1764 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001765 if (mDeviceMode == DeviceMode::POINTER) {
1766 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001767 // Since this is a synthetic event, we can consider its latency to be zero
1768 const nsecs_t readTime = when;
Harry Cutts33476232023-01-30 19:57:29 +00001769 out += dispatchPointerGestures(when, readTime, /*policyFlags=*/0, /*isTimeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001770 }
Michael Wright227c5542020-07-02 18:30:52 +01001771 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001772 if (mExternalStylusFusionTimeout <= when) {
Harry Cutts33476232023-01-30 19:57:29 +00001773 out += processRawTouches(/*timeout=*/true);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001774 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1775 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1776 }
1777 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001778 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001779}
1780
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001781std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1782 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001783 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001784 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001785 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001786 // The following three cases are handled here:
1787 // - We're in the middle of a fused stream of data;
1788 // - We're waiting on external stylus data before dispatching the initial down; or
1789 // - Only the button state, which is not reported through a specific pointer, has changed.
1790 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001791 mExternalStylusDataPending = true;
Harry Cutts33476232023-01-30 19:57:29 +00001792 out += processRawTouches(/*timeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001793 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001794 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001795}
1796
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001797std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1798 uint32_t policyFlags, bool& outConsumed) {
1799 outConsumed = false;
1800 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001801 // Check for release of a virtual key.
1802 if (mCurrentVirtualKey.down) {
1803 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1804 // Pointer went up while virtual key was down.
1805 mCurrentVirtualKey.down = false;
1806 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001807 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1808 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1809 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001810 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1811 AKEY_EVENT_FLAG_FROM_SYSTEM |
1812 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001813 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001814 outConsumed = true;
1815 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001816 }
1817
1818 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1819 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1820 const RawPointerData::Pointer& pointer =
1821 mCurrentRawState.rawPointerData.pointerForId(id);
1822 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1823 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1824 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001825 outConsumed = true;
1826 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001827 }
1828 }
1829
1830 // Pointer left virtual key area or another pointer also went down.
1831 // Send key cancellation but do not consume the touch yet.
1832 // This is useful when the user swipes through from the virtual key area
1833 // into the main display surface.
1834 mCurrentVirtualKey.down = false;
1835 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001836 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1837 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001838 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1839 AKEY_EVENT_FLAG_FROM_SYSTEM |
1840 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1841 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001842 }
1843 }
1844
1845 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1846 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1847 // Pointer just went down. Check for virtual key press or off-screen touches.
1848 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1849 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001850 // Skip checking whether the pointer is inside the physical frame if the device is in
1851 // unscaled mode.
1852 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1853 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001854 // If exactly one pointer went down, check for virtual key hit.
1855 // Otherwise we will drop the entire stroke.
1856 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1857 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1858 if (virtualKey) {
1859 mCurrentVirtualKey.down = true;
1860 mCurrentVirtualKey.downTime = when;
1861 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1862 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1863 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001864 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1865 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001866
1867 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001868 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1869 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1870 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001871 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1872 AKEY_EVENT_ACTION_DOWN,
1873 AKEY_EVENT_FLAG_FROM_SYSTEM |
1874 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001875 }
1876 }
1877 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001878 outConsumed = true;
1879 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001880 }
1881 }
1882
1883 // Disable all virtual key touches that happen within a short time interval of the
1884 // most recent touch within the screen area. The idea is to filter out stray
1885 // virtual key presses when interacting with the touch screen.
1886 //
1887 // Problems we're trying to solve:
1888 //
1889 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1890 // virtual key area that is implemented by a separate touch panel and accidentally
1891 // triggers a virtual key.
1892 //
1893 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1894 // area and accidentally triggers a virtual key. This often happens when virtual keys
1895 // are layed out below the screen near to where the on screen keyboard's space bar
1896 // is displayed.
1897 if (mConfig.virtualKeyQuietTime > 0 &&
1898 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001899 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001900 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001901 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001902}
1903
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001904NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1905 uint32_t policyFlags, int32_t keyEventAction,
1906 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001907 int32_t keyCode = mCurrentVirtualKey.keyCode;
1908 int32_t scanCode = mCurrentVirtualKey.scanCode;
1909 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001910 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001911 policyFlags |= POLICY_FLAG_VIRTUAL;
1912
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001913 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1914 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1915 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001916}
1917
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001918std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1919 uint32_t policyFlags) {
1920 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001921 if (mCurrentMotionAborted) {
1922 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001923 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001924 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001925 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1926 if (!currentIdBits.isEmpty()) {
1927 int32_t metaState = getContext()->getGlobalMetaState();
1928 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001929 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001930 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1931 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001932 mCurrentCookedState.cookedPointerData.pointerProperties,
1933 mCurrentCookedState.cookedPointerData.pointerCoords,
1934 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1935 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1936 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001937 mCurrentMotionAborted = true;
1938 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001939 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001940}
1941
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001942// Updates pointer coords and properties for pointers with specified ids that have moved.
1943// Returns true if any of them changed.
1944static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1945 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1946 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1947 BitSet32 idBits) {
1948 bool changed = false;
1949 while (!idBits.isEmpty()) {
1950 uint32_t id = idBits.clearFirstMarkedBit();
1951 uint32_t inIndex = inIdToIndex[id];
1952 uint32_t outIndex = outIdToIndex[id];
1953
1954 const PointerProperties& curInProperties = inProperties[inIndex];
1955 const PointerCoords& curInCoords = inCoords[inIndex];
1956 PointerProperties& curOutProperties = outProperties[outIndex];
1957 PointerCoords& curOutCoords = outCoords[outIndex];
1958
1959 if (curInProperties != curOutProperties) {
1960 curOutProperties.copyFrom(curInProperties);
1961 changed = true;
1962 }
1963
1964 if (curInCoords != curOutCoords) {
1965 curOutCoords.copyFrom(curInCoords);
1966 changed = true;
1967 }
1968 }
1969 return changed;
1970}
1971
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001972std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1973 uint32_t policyFlags) {
1974 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001975 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1976 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1977 int32_t metaState = getContext()->getGlobalMetaState();
1978 int32_t buttonState = mCurrentCookedState.buttonState;
1979
1980 if (currentIdBits == lastIdBits) {
1981 if (!currentIdBits.isEmpty()) {
1982 // No pointer id changes so this is a move event.
1983 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001984 out.push_back(
1985 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1986 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1987 mCurrentCookedState.cookedPointerData.pointerProperties,
1988 mCurrentCookedState.cookedPointerData.pointerCoords,
1989 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1990 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1991 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001992 }
1993 } else {
1994 // There may be pointers going up and pointers going down and pointers moving
1995 // all at the same time.
1996 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1997 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1998 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1999 BitSet32 dispatchedIdBits(lastIdBits.value);
2000
2001 // Update last coordinates of pointers that have moved so that we observe the new
2002 // pointer positions at the same time as other pointers that have just gone up.
2003 bool moveNeeded =
2004 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
2005 mCurrentCookedState.cookedPointerData.pointerCoords,
2006 mCurrentCookedState.cookedPointerData.idToIndex,
2007 mLastCookedState.cookedPointerData.pointerProperties,
2008 mLastCookedState.cookedPointerData.pointerCoords,
2009 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
2010 if (buttonState != mLastCookedState.buttonState) {
2011 moveNeeded = true;
2012 }
2013
2014 // Dispatch pointer up events.
2015 while (!upIdBits.isEmpty()) {
2016 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002017 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002018 if (isCanceled) {
2019 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2020 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002021 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2022 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2023 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2024 buttonState, 0,
2025 mLastCookedState.cookedPointerData.pointerProperties,
2026 mLastCookedState.cookedPointerData.pointerCoords,
2027 mLastCookedState.cookedPointerData.idToIndex,
2028 dispatchedIdBits, upId, mOrientedXPrecision,
2029 mOrientedYPrecision, mDownTime,
2030 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002031 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002032 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002033 }
2034
2035 // Dispatch move events if any of the remaining pointers moved from their old locations.
2036 // Although applications receive new locations as part of individual pointer up
2037 // events, they do not generally handle them except when presented in a move event.
2038 if (moveNeeded && !moveIdBits.isEmpty()) {
2039 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002040 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2041 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2042 mCurrentCookedState.cookedPointerData.pointerProperties,
2043 mCurrentCookedState.cookedPointerData.pointerCoords,
2044 mCurrentCookedState.cookedPointerData.idToIndex,
2045 dispatchedIdBits, -1, mOrientedXPrecision,
2046 mOrientedYPrecision, mDownTime,
2047 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002048 }
2049
2050 // Dispatch pointer down events using the new pointer locations.
2051 while (!downIdBits.isEmpty()) {
2052 uint32_t downId = downIdBits.clearFirstMarkedBit();
2053 dispatchedIdBits.markBit(downId);
2054
2055 if (dispatchedIdBits.count() == 1) {
2056 // First pointer is going down. Set down time.
2057 mDownTime = when;
2058 }
2059
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002060 out.push_back(
2061 dispatchMotion(when, readTime, policyFlags, mSource,
2062 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2063 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2064 mCurrentCookedState.cookedPointerData.pointerCoords,
2065 mCurrentCookedState.cookedPointerData.idToIndex,
2066 dispatchedIdBits, downId, mOrientedXPrecision,
2067 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002068 }
2069 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002070 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002071}
2072
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002073std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2074 uint32_t policyFlags) {
2075 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002076 if (mSentHoverEnter &&
2077 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2078 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2079 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002080 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2081 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2082 mLastCookedState.buttonState, 0,
2083 mLastCookedState.cookedPointerData.pointerProperties,
2084 mLastCookedState.cookedPointerData.pointerCoords,
2085 mLastCookedState.cookedPointerData.idToIndex,
2086 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2087 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2088 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002089 mSentHoverEnter = false;
2090 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002091 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002092}
2093
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002094std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2095 uint32_t policyFlags) {
2096 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002097 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2098 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2099 int32_t metaState = getContext()->getGlobalMetaState();
2100 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002101 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2102 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2103 mCurrentRawState.buttonState, 0,
2104 mCurrentCookedState.cookedPointerData.pointerProperties,
2105 mCurrentCookedState.cookedPointerData.pointerCoords,
2106 mCurrentCookedState.cookedPointerData.idToIndex,
2107 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2108 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2109 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002110 mSentHoverEnter = true;
2111 }
2112
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002113 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2114 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2115 mCurrentRawState.buttonState, 0,
2116 mCurrentCookedState.cookedPointerData.pointerProperties,
2117 mCurrentCookedState.cookedPointerData.pointerCoords,
2118 mCurrentCookedState.cookedPointerData.idToIndex,
2119 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2120 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2121 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002122 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002123 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002124}
2125
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002126std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2127 uint32_t policyFlags) {
2128 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002129 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2130 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2131 const int32_t metaState = getContext()->getGlobalMetaState();
2132 int32_t buttonState = mLastCookedState.buttonState;
2133 while (!releasedButtons.isEmpty()) {
2134 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2135 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002136 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2137 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2138 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002139 mLastCookedState.cookedPointerData.pointerProperties,
2140 mLastCookedState.cookedPointerData.pointerCoords,
2141 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002142 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2143 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002144 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002145 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002146}
2147
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002148std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2149 uint32_t policyFlags) {
2150 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002151 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2152 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2153 const int32_t metaState = getContext()->getGlobalMetaState();
2154 int32_t buttonState = mLastCookedState.buttonState;
2155 while (!pressedButtons.isEmpty()) {
2156 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2157 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002158 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2159 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2160 buttonState, 0,
2161 mCurrentCookedState.cookedPointerData.pointerProperties,
2162 mCurrentCookedState.cookedPointerData.pointerCoords,
2163 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2164 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2165 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002166 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002167 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002168}
2169
LiZhihong758eb562022-11-03 15:28:29 +08002170std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonRelease(nsecs_t when,
2171 uint32_t policyFlags,
2172 BitSet32 idBits,
2173 nsecs_t readTime) {
2174 std::list<NotifyArgs> out;
2175 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2176 const int32_t metaState = getContext()->getGlobalMetaState();
2177 int32_t buttonState = mLastCookedState.buttonState;
2178
2179 while (!releasedButtons.isEmpty()) {
2180 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2181 buttonState &= ~actionButton;
2182 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2183 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2184 metaState, buttonState, 0,
2185 mPointerGesture.lastGestureProperties,
2186 mPointerGesture.lastGestureCoords,
2187 mPointerGesture.lastGestureIdToIndex, idBits, -1,
2188 mOrientedXPrecision, mOrientedYPrecision,
2189 mPointerGesture.downTime, MotionClassification::NONE));
2190 }
2191 return out;
2192}
2193
2194std::list<NotifyArgs> TouchInputMapper::dispatchGestureButtonPress(nsecs_t when,
2195 uint32_t policyFlags,
2196 BitSet32 idBits,
2197 nsecs_t readTime) {
2198 std::list<NotifyArgs> out;
2199 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2200 const int32_t metaState = getContext()->getGlobalMetaState();
2201 int32_t buttonState = mLastCookedState.buttonState;
2202
2203 while (!pressedButtons.isEmpty()) {
2204 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2205 buttonState |= actionButton;
2206 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2207 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2208 buttonState, 0, mPointerGesture.currentGestureProperties,
2209 mPointerGesture.currentGestureCoords,
2210 mPointerGesture.currentGestureIdToIndex, idBits, -1,
2211 mOrientedXPrecision, mOrientedYPrecision,
2212 mPointerGesture.downTime, MotionClassification::NONE));
2213 }
2214 return out;
2215}
2216
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002217const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2218 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2219 return cookedPointerData.touchingIdBits;
2220 }
2221 return cookedPointerData.hoveringIdBits;
2222}
2223
2224void TouchInputMapper::cookPointerData() {
2225 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2226
2227 mCurrentCookedState.cookedPointerData.clear();
2228 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2229 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2230 mCurrentRawState.rawPointerData.hoveringIdBits;
2231 mCurrentCookedState.cookedPointerData.touchingIdBits =
2232 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002233 mCurrentCookedState.cookedPointerData.canceledIdBits =
2234 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002235
2236 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2237 mCurrentCookedState.buttonState = 0;
2238 } else {
2239 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2240 }
2241
2242 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002243 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002244 for (uint32_t i = 0; i < currentPointerCount; i++) {
2245 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2246
2247 // Size
2248 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2249 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002250 case Calibration::SizeCalibration::GEOMETRIC:
2251 case Calibration::SizeCalibration::DIAMETER:
2252 case Calibration::SizeCalibration::BOX:
2253 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002254 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2255 touchMajor = in.touchMajor;
2256 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2257 toolMajor = in.toolMajor;
2258 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2259 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2260 : in.touchMajor;
2261 } else if (mRawPointerAxes.touchMajor.valid) {
2262 toolMajor = touchMajor = in.touchMajor;
2263 toolMinor = touchMinor =
2264 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2265 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2266 : in.touchMajor;
2267 } else if (mRawPointerAxes.toolMajor.valid) {
2268 touchMajor = toolMajor = in.toolMajor;
2269 touchMinor = toolMinor =
2270 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2271 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2272 : in.toolMajor;
2273 } else {
2274 ALOG_ASSERT(false,
2275 "No touch or tool axes. "
2276 "Size calibration should have been resolved to NONE.");
2277 touchMajor = 0;
2278 touchMinor = 0;
2279 toolMajor = 0;
2280 toolMinor = 0;
2281 size = 0;
2282 }
2283
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002284 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002285 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2286 if (touchingCount > 1) {
2287 touchMajor /= touchingCount;
2288 touchMinor /= touchingCount;
2289 toolMajor /= touchingCount;
2290 toolMinor /= touchingCount;
2291 size /= touchingCount;
2292 }
2293 }
2294
Michael Wright227c5542020-07-02 18:30:52 +01002295 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002296 touchMajor *= mGeometricScale;
2297 touchMinor *= mGeometricScale;
2298 toolMajor *= mGeometricScale;
2299 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002300 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002301 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2302 touchMinor = touchMajor;
2303 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2304 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002305 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002306 touchMinor = touchMajor;
2307 toolMinor = toolMajor;
2308 }
2309
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002310 mCalibration.applySizeScaleAndBias(touchMajor);
2311 mCalibration.applySizeScaleAndBias(touchMinor);
2312 mCalibration.applySizeScaleAndBias(toolMajor);
2313 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002314 size *= mSizeScale;
2315 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002316 case Calibration::SizeCalibration::DEFAULT:
2317 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2318 break;
2319 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002320 touchMajor = 0;
2321 touchMinor = 0;
2322 toolMajor = 0;
2323 toolMinor = 0;
2324 size = 0;
2325 break;
2326 }
2327
2328 // Pressure
2329 float pressure;
2330 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002331 case Calibration::PressureCalibration::PHYSICAL:
2332 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002333 pressure = in.pressure * mPressureScale;
2334 break;
2335 default:
2336 pressure = in.isHovering ? 0 : 1;
2337 break;
2338 }
2339
2340 // Tilt and Orientation
2341 float tilt;
2342 float orientation;
2343 if (mHaveTilt) {
2344 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2345 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002346 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002347 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2348 } else {
2349 tilt = 0;
2350
2351 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002352 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002353 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002354 break;
Michael Wright227c5542020-07-02 18:30:52 +01002355 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002356 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2357 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2358 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002359 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002360 float confidence = hypotf(c1, c2);
2361 float scale = 1.0f + confidence / 16.0f;
2362 touchMajor *= scale;
2363 touchMinor /= scale;
2364 toolMajor *= scale;
2365 toolMinor /= scale;
2366 } else {
2367 orientation = 0;
2368 }
2369 break;
2370 }
2371 default:
2372 orientation = 0;
2373 }
2374 }
2375
2376 // Distance
2377 float distance;
2378 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002379 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002380 distance = in.distance * mDistanceScale;
2381 break;
2382 default:
2383 distance = 0;
2384 }
2385
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002386 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2387 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002388 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2389 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002390
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391 // Write output coords.
2392 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2393 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002394 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2395 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002396 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2397 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2398 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2399 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2400 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2401 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2402 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002403 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2404 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002405
Chris Ye364fdb52020-08-05 15:07:56 -07002406 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002407 uint32_t id = in.id;
2408 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2409 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2410 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002411 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2412 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002413 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2414 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2415 }
2416
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002417 // Write output properties.
2418 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002419 properties.clear();
2420 properties.id = id;
2421 properties.toolType = in.toolType;
2422
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002423 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002424 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002425 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002426 }
2427}
2428
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002429std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2430 uint32_t policyFlags,
2431 PointerUsage pointerUsage) {
2432 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002433 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002434 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002435 mPointerUsage = pointerUsage;
2436 }
2437
2438 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002439 case PointerUsage::GESTURES:
Harry Cutts33476232023-01-30 19:57:29 +00002440 out += dispatchPointerGestures(when, readTime, policyFlags, /*isTimeout=*/false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002441 break;
Michael Wright227c5542020-07-02 18:30:52 +01002442 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002443 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002444 break;
Michael Wright227c5542020-07-02 18:30:52 +01002445 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002446 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002447 break;
Michael Wright227c5542020-07-02 18:30:52 +01002448 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002449 break;
2450 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002451 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002452}
2453
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002454std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2455 uint32_t policyFlags) {
2456 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002457 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002458 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002459 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002460 break;
Michael Wright227c5542020-07-02 18:30:52 +01002461 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002462 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002463 break;
Michael Wright227c5542020-07-02 18:30:52 +01002464 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002465 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002466 break;
Michael Wright227c5542020-07-02 18:30:52 +01002467 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002468 break;
2469 }
2470
Michael Wright227c5542020-07-02 18:30:52 +01002471 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002472 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002473}
2474
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002475std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2476 uint32_t policyFlags,
2477 bool isTimeout) {
2478 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002479 // Update current gesture coordinates.
2480 bool cancelPreviousGesture, finishPreviousGesture;
2481 bool sendEvents =
2482 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2483 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002484 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002485 }
2486 if (finishPreviousGesture) {
2487 cancelPreviousGesture = false;
2488 }
2489
2490 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002491 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002492 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002493 if (finishPreviousGesture || cancelPreviousGesture) {
2494 mPointerController->clearSpots();
2495 }
2496
Michael Wright227c5542020-07-02 18:30:52 +01002497 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002498 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2499 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002500 mPointerGesture.currentGestureIdBits,
2501 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002502 }
2503 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002504 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002505 }
2506
2507 // Show or hide the pointer if needed.
2508 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002509 case PointerGesture::Mode::NEUTRAL:
2510 case PointerGesture::Mode::QUIET:
2511 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2512 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002513 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002514 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002515 }
2516 break;
Michael Wright227c5542020-07-02 18:30:52 +01002517 case PointerGesture::Mode::TAP:
2518 case PointerGesture::Mode::TAP_DRAG:
2519 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2520 case PointerGesture::Mode::HOVER:
2521 case PointerGesture::Mode::PRESS:
2522 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002523 // Unfade the pointer when the current gesture manipulates the
2524 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002525 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002526 break;
Michael Wright227c5542020-07-02 18:30:52 +01002527 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002528 // Fade the pointer when the current gesture manipulates a different
2529 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002530 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002531 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002532 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002533 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002534 }
2535 break;
2536 }
2537
2538 // Send events!
2539 int32_t metaState = getContext()->getGlobalMetaState();
2540 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002541 const MotionClassification classification =
2542 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2543 ? MotionClassification::TWO_FINGER_SWIPE
2544 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002545
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002546 uint32_t flags = 0;
2547
2548 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2549 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2550 }
2551
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002552 // Update last coordinates of pointers that have moved so that we observe the new
2553 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002554 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2555 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2556 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2557 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2558 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2559 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002560 bool moveNeeded = false;
2561 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2562 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2563 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2564 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2565 mPointerGesture.lastGestureIdBits.value);
2566 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2567 mPointerGesture.currentGestureCoords,
2568 mPointerGesture.currentGestureIdToIndex,
2569 mPointerGesture.lastGestureProperties,
2570 mPointerGesture.lastGestureCoords,
2571 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2572 if (buttonState != mLastCookedState.buttonState) {
2573 moveNeeded = true;
2574 }
2575 }
2576
2577 // Send motion events for all pointers that went up or were canceled.
2578 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2579 if (!dispatchedGestureIdBits.isEmpty()) {
2580 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002581 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002582 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002583 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002584 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2585 mPointerGesture.lastGestureProperties,
2586 mPointerGesture.lastGestureCoords,
2587 mPointerGesture.lastGestureIdToIndex,
2588 dispatchedGestureIdBits, -1, 0, 0,
2589 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002590
2591 dispatchedGestureIdBits.clear();
2592 } else {
2593 BitSet32 upGestureIdBits;
2594 if (finishPreviousGesture) {
2595 upGestureIdBits = dispatchedGestureIdBits;
2596 } else {
2597 upGestureIdBits.value =
2598 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2599 }
2600 while (!upGestureIdBits.isEmpty()) {
LiZhihong758eb562022-11-03 15:28:29 +08002601 if (((mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2602 (mLastCookedState.buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2603 mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2604 out += dispatchGestureButtonRelease(when, policyFlags, dispatchedGestureIdBits,
2605 readTime);
2606 }
2607 const uint32_t id = upGestureIdBits.clearFirstMarkedBit();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002608 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2609 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2610 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2611 mPointerGesture.lastGestureProperties,
2612 mPointerGesture.lastGestureCoords,
2613 mPointerGesture.lastGestureIdToIndex,
2614 dispatchedGestureIdBits, id, 0, 0,
2615 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002616
2617 dispatchedGestureIdBits.clearBit(id);
2618 }
2619 }
2620 }
2621
2622 // Send motion events for all pointers that moved.
2623 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002624 out.push_back(
2625 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2626 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2627 mPointerGesture.currentGestureProperties,
2628 mPointerGesture.currentGestureCoords,
2629 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2630 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002631 }
2632
2633 // Send motion events for all pointers that went down.
2634 if (down) {
2635 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2636 ~dispatchedGestureIdBits.value);
2637 while (!downGestureIdBits.isEmpty()) {
2638 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2639 dispatchedGestureIdBits.markBit(id);
2640
2641 if (dispatchedGestureIdBits.count() == 1) {
2642 mPointerGesture.downTime = when;
2643 }
2644
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002645 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2646 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2647 buttonState, 0, mPointerGesture.currentGestureProperties,
2648 mPointerGesture.currentGestureCoords,
2649 mPointerGesture.currentGestureIdToIndex,
2650 dispatchedGestureIdBits, id, 0, 0,
2651 mPointerGesture.downTime, classification));
LiZhihong758eb562022-11-03 15:28:29 +08002652 if (((buttonState & AMOTION_EVENT_BUTTON_PRIMARY) != 0 ||
2653 (buttonState & AMOTION_EVENT_BUTTON_SECONDARY) != 0) &&
2654 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
2655 out += dispatchGestureButtonPress(when, policyFlags, dispatchedGestureIdBits,
2656 readTime);
2657 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002658 }
2659 }
2660
2661 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002662 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002663 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2664 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2665 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2666 mPointerGesture.currentGestureProperties,
2667 mPointerGesture.currentGestureCoords,
2668 mPointerGesture.currentGestureIdToIndex,
2669 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2670 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002671 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2672 // Synthesize a hover move event after all pointers go up to indicate that
2673 // the pointer is hovering again even if the user is not currently touching
2674 // the touch pad. This ensures that a view will receive a fresh hover enter
2675 // event after a tap.
Prabir Pradhan2719e822023-02-28 17:39:36 +00002676 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002677
2678 PointerProperties pointerProperties;
2679 pointerProperties.clear();
2680 pointerProperties.id = 0;
2681 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2682
2683 PointerCoords pointerCoords;
2684 pointerCoords.clear();
2685 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2686 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2687
2688 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002689 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2690 mSource, displayId, policyFlags,
2691 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2692 buttonState, MotionClassification::NONE,
2693 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2694 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2695 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002696 }
2697
2698 // Update state.
2699 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2700 if (!down) {
2701 mPointerGesture.lastGestureIdBits.clear();
2702 } else {
2703 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2704 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2705 uint32_t id = idBits.clearFirstMarkedBit();
2706 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2707 mPointerGesture.lastGestureProperties[index].copyFrom(
2708 mPointerGesture.currentGestureProperties[index]);
2709 mPointerGesture.lastGestureCoords[index].copyFrom(
2710 mPointerGesture.currentGestureCoords[index]);
2711 mPointerGesture.lastGestureIdToIndex[id] = index;
2712 }
2713 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002714 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002715}
2716
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002717std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2718 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002719 const MotionClassification classification =
2720 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2721 ? MotionClassification::TWO_FINGER_SWIPE
2722 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002723 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002724 // Cancel previously dispatches pointers.
2725 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2726 int32_t metaState = getContext()->getGlobalMetaState();
2727 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002728 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002729 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2730 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002731 mPointerGesture.lastGestureProperties,
2732 mPointerGesture.lastGestureCoords,
2733 mPointerGesture.lastGestureIdToIndex,
2734 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2735 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002736 }
2737
2738 // Reset the current pointer gesture.
2739 mPointerGesture.reset();
2740 mPointerVelocityControl.reset();
2741
2742 // Remove any current spots.
2743 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002744 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002745 mPointerController->clearSpots();
2746 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002747 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002748}
2749
2750bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2751 bool* outFinishPreviousGesture, bool isTimeout) {
2752 *outCancelPreviousGesture = false;
2753 *outFinishPreviousGesture = false;
2754
2755 // Handle TAP timeout.
2756 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002757 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002758
Michael Wright227c5542020-07-02 18:30:52 +01002759 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002760 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2761 // The tap/drag timeout has not yet expired.
2762 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2763 mConfig.pointerGestureTapDragInterval);
2764 } else {
2765 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002766 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002767 *outFinishPreviousGesture = true;
2768
2769 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002770 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002771 mPointerGesture.currentGestureIdBits.clear();
2772
2773 mPointerVelocityControl.reset();
2774 return true;
2775 }
2776 }
2777
2778 // We did not handle this timeout.
2779 return false;
2780 }
2781
2782 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2783 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2784
2785 // Update the velocity tracker.
2786 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002787 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002788 uint32_t id = idBits.clearFirstMarkedBit();
2789 const RawPointerData::Pointer& pointer =
2790 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakou8d232032023-01-11 08:17:21 -08002791 const float x = pointer.x * mPointerXMovementScale;
2792 const float y = pointer.y * mPointerYMovementScale;
2793 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_X, x);
2794 mPointerGesture.velocityTracker.addMovement(when, id, AMOTION_EVENT_AXIS_Y, y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002795 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002796 }
2797
2798 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2799 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002800 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2801 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2802 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002803 mPointerGesture.resetTap();
2804 }
2805
2806 // Pick a new active touch id if needed.
2807 // Choose an arbitrary pointer that just went down, if there is one.
2808 // Otherwise choose an arbitrary remaining pointer.
2809 // This guarantees we always have an active touch id when there is at least one pointer.
2810 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002811 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002812 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002813 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002814 mPointerGesture.firstTouchTime = when;
2815 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002816 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2817 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2818 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2819 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002820 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002821 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002822
2823 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002824 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002825 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002826 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2827 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2828 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002829 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002830 *outFinishPreviousGesture = true;
2831 }
2832
2833 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002834 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002835 mPointerGesture.currentGestureIdBits.clear();
2836
2837 mPointerVelocityControl.reset();
2838 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2839 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2840 // The pointer follows the active touch point.
2841 // Emit DOWN, MOVE, UP events at the pointer location.
2842 //
2843 // Only the active touch matters; other fingers are ignored. This policy helps
2844 // to handle the case where the user places a second finger on the touch pad
2845 // to apply the necessary force to depress an integrated button below the surface.
2846 // We don't want the second finger to be delivered to applications.
2847 //
2848 // For this to work well, we need to make sure to track the pointer that is really
2849 // active. If the user first puts one finger down to click then adds another
2850 // finger to drag then the active pointer should switch to the finger that is
2851 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002852 ALOGD_IF(DEBUG_GESTURES,
2853 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2854 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002855 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002856 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002857 *outFinishPreviousGesture = true;
2858 mPointerGesture.activeGestureId = 0;
2859 }
2860
2861 // Switch pointers if needed.
2862 // Find the fastest pointer and follow it.
2863 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002864 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002865 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002866 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002867 ALOGD_IF(DEBUG_GESTURES,
2868 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2869 "bestSpeed=%0.3f",
2870 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002871 }
2872 }
2873
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002874 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002875 // When using spots, the click will occur at the position of the anchor
2876 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002877 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002878 } else {
2879 mPointerVelocityControl.reset();
2880 }
2881
Prabir Pradhan2719e822023-02-28 17:39:36 +00002882 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002883
Michael Wright227c5542020-07-02 18:30:52 +01002884 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002885 mPointerGesture.currentGestureIdBits.clear();
2886 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2887 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2888 mPointerGesture.currentGestureProperties[0].clear();
2889 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2890 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2891 mPointerGesture.currentGestureCoords[0].clear();
2892 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2893 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2894 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2895 } else if (currentFingerCount == 0) {
2896 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002897 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002898 *outFinishPreviousGesture = true;
2899 }
2900
2901 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2902 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2903 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002904 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2905 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002906 lastFingerCount == 1) {
2907 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00002908 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002909 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2910 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002911 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002912
2913 mPointerGesture.tapUpTime = when;
2914 getContext()->requestTimeoutAtTime(when +
2915 mConfig.pointerGestureTapDragInterval);
2916
2917 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002918 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002919 mPointerGesture.currentGestureIdBits.clear();
2920 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2921 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2922 mPointerGesture.currentGestureProperties[0].clear();
2923 mPointerGesture.currentGestureProperties[0].id =
2924 mPointerGesture.activeGestureId;
2925 mPointerGesture.currentGestureProperties[0].toolType =
2926 AMOTION_EVENT_TOOL_TYPE_FINGER;
2927 mPointerGesture.currentGestureCoords[0].clear();
2928 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2929 mPointerGesture.tapX);
2930 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2931 mPointerGesture.tapY);
2932 mPointerGesture.currentGestureCoords[0]
2933 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2934
2935 tapped = true;
2936 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002937 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2938 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002939 }
2940 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002941 if (DEBUG_GESTURES) {
2942 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2943 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2944 (when - mPointerGesture.tapDownTime) * 0.000001f);
2945 } else {
2946 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2947 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002948 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002949 }
2950 }
2951
2952 mPointerVelocityControl.reset();
2953
2954 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002955 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002956 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002957 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002958 mPointerGesture.currentGestureIdBits.clear();
2959 }
2960 } else if (currentFingerCount == 1) {
2961 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2962 // The pointer follows the active touch point.
2963 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2964 // When in TAP_DRAG, emit MOVE events at the pointer location.
2965 ALOG_ASSERT(activeTouchId >= 0);
2966
Michael Wright227c5542020-07-02 18:30:52 +01002967 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2968 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002969 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00002970 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002971 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2972 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002973 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002974 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002975 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2976 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002977 }
2978 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002979 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2980 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002981 }
Michael Wright227c5542020-07-02 18:30:52 +01002982 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2983 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002984 }
2985
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002986 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002987 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002988 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002989 } else {
2990 mPointerVelocityControl.reset();
2991 }
2992
2993 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002994 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00002995 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002996 down = true;
2997 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002998 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01002999 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003000 *outFinishPreviousGesture = true;
3001 }
3002 mPointerGesture.activeGestureId = 0;
3003 down = false;
3004 }
3005
Prabir Pradhan2719e822023-02-28 17:39:36 +00003006 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003007
3008 mPointerGesture.currentGestureIdBits.clear();
3009 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3010 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3011 mPointerGesture.currentGestureProperties[0].clear();
3012 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3013 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3014 mPointerGesture.currentGestureCoords[0].clear();
3015 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3016 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3017 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3018 down ? 1.0f : 0.0f);
3019
3020 if (lastFingerCount == 0 && currentFingerCount != 0) {
3021 mPointerGesture.resetTap();
3022 mPointerGesture.tapDownTime = when;
3023 mPointerGesture.tapX = x;
3024 mPointerGesture.tapY = y;
3025 }
3026 } else {
3027 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003028 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003029 }
3030
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003031 if (DEBUG_GESTURES) {
3032 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3033 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3034 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3035 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3036 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3037 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3038 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3039 uint32_t id = idBits.clearFirstMarkedBit();
3040 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3041 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3042 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3043 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3044 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3045 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3046 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3047 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3048 }
3049 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3050 uint32_t id = idBits.clearFirstMarkedBit();
3051 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3052 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3053 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3054 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3055 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3056 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3057 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3058 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3059 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003060 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003061 return true;
3062}
3063
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003064bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3065 if (mPointerGesture.activeTouchId < 0) {
3066 mPointerGesture.resetQuietTime();
3067 return false;
3068 }
3069
3070 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3071 return true;
3072 }
3073
3074 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3075 bool isQuietTime = false;
3076 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3077 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3078 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3079 currentFingerCount < 2) {
3080 // Enter quiet time when exiting swipe or freeform state.
3081 // This is to prevent accidentally entering the hover state and flinging the
3082 // pointer when finishing a swipe and there is still one pointer left onscreen.
3083 isQuietTime = true;
3084 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3085 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3086 // Enter quiet time when releasing the button and there are still two or more
3087 // fingers down. This may indicate that one finger was used to press the button
3088 // but it has not gone up yet.
3089 isQuietTime = true;
3090 }
3091 if (isQuietTime) {
3092 mPointerGesture.quietTime = when;
3093 }
3094 return isQuietTime;
3095}
3096
3097std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3098 int32_t bestId = -1;
3099 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3100 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3101 uint32_t id = idBits.clearFirstMarkedBit();
3102 std::optional<float> vx =
3103 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3104 std::optional<float> vy =
3105 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3106 if (vx && vy) {
3107 float speed = hypotf(*vx, *vy);
3108 if (speed > bestSpeed) {
3109 bestId = id;
3110 bestSpeed = speed;
3111 }
3112 }
3113 }
3114 return std::make_pair(bestId, bestSpeed);
3115}
3116
3117void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3118 bool* finishPreviousGesture) {
3119 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3120 // to move before deciding what to do.
3121 //
3122 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3123 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3124 // just a press or long-press at the pointer location.
3125 //
3126 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3127 // pointer location.
3128 //
3129 // When the two fingers move enough or when additional fingers are added, we make a decision to
3130 // transition into SWIPE or FREEFORM mode accordingly.
3131 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3132 ALOG_ASSERT(activeTouchId >= 0);
3133
3134 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3135 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3136 bool settled =
3137 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3138 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3139 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3140 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3141 *finishPreviousGesture = true;
3142 } else if (!settled && currentFingerCount > lastFingerCount) {
3143 // Additional pointers have gone down but not yet settled.
3144 // Reset the gesture.
3145 ALOGD_IF(DEBUG_GESTURES,
3146 "Gestures: Resetting gesture since additional pointers went down for "
3147 "MULTITOUCH, settle time remaining %0.3fms",
3148 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3149 when) * 0.000001f);
3150 *cancelPreviousGesture = true;
3151 } else {
3152 // Continue previous gesture.
3153 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3154 }
3155
3156 if (*finishPreviousGesture || *cancelPreviousGesture) {
3157 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3158 mPointerGesture.activeGestureId = 0;
3159 mPointerGesture.referenceIdBits.clear();
3160 mPointerVelocityControl.reset();
3161
3162 // Use the centroid and pointer location as the reference points for the gesture.
3163 ALOGD_IF(DEBUG_GESTURES,
3164 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3165 "%0.3fms",
3166 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3167 when) * 0.000001f);
3168 mCurrentRawState.rawPointerData
3169 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3170 &mPointerGesture.referenceTouchY);
Prabir Pradhan2719e822023-02-28 17:39:36 +00003171 std::tie(mPointerGesture.referenceGestureX, mPointerGesture.referenceGestureY) =
3172 mPointerController->getPosition();
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003173 }
3174
3175 // Clear the reference deltas for fingers not yet included in the reference calculation.
3176 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3177 ~mPointerGesture.referenceIdBits.value);
3178 !idBits.isEmpty();) {
3179 uint32_t id = idBits.clearFirstMarkedBit();
3180 mPointerGesture.referenceDeltas[id].dx = 0;
3181 mPointerGesture.referenceDeltas[id].dy = 0;
3182 }
3183 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3184
3185 // Add delta for all fingers and calculate a common movement delta.
3186 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3187 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3188 mCurrentCookedState.fingerIdBits.value);
3189 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3190 bool first = (idBits == commonIdBits);
3191 uint32_t id = idBits.clearFirstMarkedBit();
3192 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3193 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3194 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3195 delta.dx += cpd.x - lpd.x;
3196 delta.dy += cpd.y - lpd.y;
3197
3198 if (first) {
3199 commonDeltaRawX = delta.dx;
3200 commonDeltaRawY = delta.dy;
3201 } else {
3202 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3203 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3204 }
3205 }
3206
3207 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3208 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3209 float dist[MAX_POINTER_ID + 1];
3210 int32_t distOverThreshold = 0;
3211 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3212 uint32_t id = idBits.clearFirstMarkedBit();
3213 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3214 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3215 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3216 distOverThreshold += 1;
3217 }
3218 }
3219
3220 // Only transition when at least two pointers have moved further than
3221 // the minimum distance threshold.
3222 if (distOverThreshold >= 2) {
3223 if (currentFingerCount > 2) {
3224 // There are more than two pointers, switch to FREEFORM.
3225 ALOGD_IF(DEBUG_GESTURES,
3226 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3227 currentFingerCount);
3228 *cancelPreviousGesture = true;
3229 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3230 } else {
3231 // There are exactly two pointers.
3232 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3233 uint32_t id1 = idBits.clearFirstMarkedBit();
3234 uint32_t id2 = idBits.firstMarkedBit();
3235 const RawPointerData::Pointer& p1 =
3236 mCurrentRawState.rawPointerData.pointerForId(id1);
3237 const RawPointerData::Pointer& p2 =
3238 mCurrentRawState.rawPointerData.pointerForId(id2);
3239 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3240 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3241 // There are two pointers but they are too far apart for a SWIPE,
3242 // switch to FREEFORM.
3243 ALOGD_IF(DEBUG_GESTURES,
3244 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3245 mutualDistance, mPointerGestureMaxSwipeWidth);
3246 *cancelPreviousGesture = true;
3247 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3248 } else {
3249 // There are two pointers. Wait for both pointers to start moving
3250 // before deciding whether this is a SWIPE or FREEFORM gesture.
3251 float dist1 = dist[id1];
3252 float dist2 = dist[id2];
3253 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3254 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3255 // Calculate the dot product of the displacement vectors.
3256 // When the vectors are oriented in approximately the same direction,
3257 // the angle betweeen them is near zero and the cosine of the angle
3258 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3259 // mag(v2).
3260 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3261 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3262 float dx1 = delta1.dx * mPointerXZoomScale;
3263 float dy1 = delta1.dy * mPointerYZoomScale;
3264 float dx2 = delta2.dx * mPointerXZoomScale;
3265 float dy2 = delta2.dy * mPointerYZoomScale;
3266 float dot = dx1 * dx2 + dy1 * dy2;
3267 float cosine = dot / (dist1 * dist2); // denominator always > 0
3268 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3269 // Pointers are moving in the same direction. Switch to SWIPE.
3270 ALOGD_IF(DEBUG_GESTURES,
3271 "Gestures: PRESS transitioned to SWIPE, "
3272 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3273 "cosine %0.3f >= %0.3f",
3274 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3275 mConfig.pointerGestureMultitouchMinDistance, cosine,
3276 mConfig.pointerGestureSwipeTransitionAngleCosine);
3277 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3278 } else {
3279 // Pointers are moving in different directions. Switch to FREEFORM.
3280 ALOGD_IF(DEBUG_GESTURES,
3281 "Gestures: PRESS transitioned to FREEFORM, "
3282 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3283 "cosine %0.3f < %0.3f",
3284 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3285 mConfig.pointerGestureMultitouchMinDistance, cosine,
3286 mConfig.pointerGestureSwipeTransitionAngleCosine);
3287 *cancelPreviousGesture = true;
3288 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3289 }
3290 }
3291 }
3292 }
3293 }
3294 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3295 // Switch from SWIPE to FREEFORM if additional pointers go down.
3296 // Cancel previous gesture.
3297 if (currentFingerCount > 2) {
3298 ALOGD_IF(DEBUG_GESTURES,
3299 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3300 currentFingerCount);
3301 *cancelPreviousGesture = true;
3302 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3303 }
3304 }
3305
3306 // Move the reference points based on the overall group motion of the fingers
3307 // except in PRESS mode while waiting for a transition to occur.
3308 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3309 (commonDeltaRawX || commonDeltaRawY)) {
3310 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3311 uint32_t id = idBits.clearFirstMarkedBit();
3312 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3313 delta.dx = 0;
3314 delta.dy = 0;
3315 }
3316
3317 mPointerGesture.referenceTouchX += commonDeltaRawX;
3318 mPointerGesture.referenceTouchY += commonDeltaRawY;
3319
3320 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3321 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3322
3323 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3324 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3325
3326 mPointerGesture.referenceGestureX += commonDeltaX;
3327 mPointerGesture.referenceGestureY += commonDeltaY;
3328 }
3329
3330 // Report gestures.
3331 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3332 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3333 // PRESS or SWIPE mode.
3334 ALOGD_IF(DEBUG_GESTURES,
3335 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3336 "currentTouchPointerCount=%d",
3337 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3338 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3339
3340 mPointerGesture.currentGestureIdBits.clear();
3341 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3342 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3343 mPointerGesture.currentGestureProperties[0].clear();
3344 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3345 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3346 mPointerGesture.currentGestureCoords[0].clear();
3347 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3348 mPointerGesture.referenceGestureX);
3349 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3350 mPointerGesture.referenceGestureY);
3351 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3352 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3353 float xOffset = static_cast<float>(commonDeltaRawX) /
3354 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3355 float yOffset = static_cast<float>(commonDeltaRawY) /
3356 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3357 mPointerGesture.currentGestureCoords[0]
3358 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3359 mPointerGesture.currentGestureCoords[0]
3360 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3361 }
3362 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3363 // FREEFORM mode.
3364 ALOGD_IF(DEBUG_GESTURES,
3365 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3366 "currentTouchPointerCount=%d",
3367 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3368 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3369
3370 mPointerGesture.currentGestureIdBits.clear();
3371
3372 BitSet32 mappedTouchIdBits;
3373 BitSet32 usedGestureIdBits;
3374 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3375 // Initially, assign the active gesture id to the active touch point
3376 // if there is one. No other touch id bits are mapped yet.
3377 if (!*cancelPreviousGesture) {
3378 mappedTouchIdBits.markBit(activeTouchId);
3379 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3380 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3381 mPointerGesture.activeGestureId;
3382 } else {
3383 mPointerGesture.activeGestureId = -1;
3384 }
3385 } else {
3386 // Otherwise, assume we mapped all touches from the previous frame.
3387 // Reuse all mappings that are still applicable.
3388 mappedTouchIdBits.value =
3389 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3390 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3391
3392 // Check whether we need to choose a new active gesture id because the
3393 // current went went up.
3394 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3395 ~mCurrentCookedState.fingerIdBits.value);
3396 !upTouchIdBits.isEmpty();) {
3397 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3398 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3399 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3400 mPointerGesture.activeGestureId = -1;
3401 break;
3402 }
3403 }
3404 }
3405
3406 ALOGD_IF(DEBUG_GESTURES,
3407 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3408 "activeGestureId=%d",
3409 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3410
3411 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3412 for (uint32_t i = 0; i < currentFingerCount; i++) {
3413 uint32_t touchId = idBits.clearFirstMarkedBit();
3414 uint32_t gestureId;
3415 if (!mappedTouchIdBits.hasBit(touchId)) {
3416 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3417 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3418 ALOGD_IF(DEBUG_GESTURES,
3419 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3420 gestureId);
3421 } else {
3422 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3423 ALOGD_IF(DEBUG_GESTURES,
3424 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3425 touchId, gestureId);
3426 }
3427 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3428 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3429
3430 const RawPointerData::Pointer& pointer =
3431 mCurrentRawState.rawPointerData.pointerForId(touchId);
3432 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3433 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3434 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3435
3436 mPointerGesture.currentGestureProperties[i].clear();
3437 mPointerGesture.currentGestureProperties[i].id = gestureId;
3438 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3439 mPointerGesture.currentGestureCoords[i].clear();
3440 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3441 mPointerGesture.referenceGestureX +
3442 deltaX);
3443 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3444 mPointerGesture.referenceGestureY +
3445 deltaY);
3446 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3447 }
3448
3449 if (mPointerGesture.activeGestureId < 0) {
3450 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3451 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3452 mPointerGesture.activeGestureId);
3453 }
3454 }
3455}
3456
Harry Cutts714d1ad2022-08-24 16:36:43 +00003457void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3458 const RawPointerData::Pointer& currentPointer =
3459 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3460 const RawPointerData::Pointer& lastPointer =
3461 mLastRawState.rawPointerData.pointerForId(pointerId);
3462 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3463 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3464
3465 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3466 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3467
3468 mPointerController->move(deltaX, deltaY);
3469}
3470
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003471std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3472 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003473 mPointerSimple.currentCoords.clear();
3474 mPointerSimple.currentProperties.clear();
3475
3476 bool down, hovering;
3477 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3478 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3479 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003480 mPointerController
3481 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3482 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003483
3484 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3485 down = !hovering;
3486
Prabir Pradhan2719e822023-02-28 17:39:36 +00003487 const auto [x, y] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003488 mPointerSimple.currentCoords.copyFrom(
3489 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3490 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3491 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3492 mPointerSimple.currentProperties.id = 0;
3493 mPointerSimple.currentProperties.toolType =
3494 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3495 } else {
3496 down = false;
3497 hovering = false;
3498 }
3499
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003500 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003501}
3502
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003503std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3504 uint32_t policyFlags) {
3505 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003506}
3507
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003508std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3509 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003510 mPointerSimple.currentCoords.clear();
3511 mPointerSimple.currentProperties.clear();
3512
3513 bool down, hovering;
3514 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3515 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003516 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003517 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003518 } else {
3519 mPointerVelocityControl.reset();
3520 }
3521
3522 down = isPointerDown(mCurrentRawState.buttonState);
3523 hovering = !down;
3524
Prabir Pradhan2719e822023-02-28 17:39:36 +00003525 const auto [x, y] = mPointerController->getPosition();
3526 const uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003527 mPointerSimple.currentCoords.copyFrom(
3528 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3529 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3530 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3531 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3532 hovering ? 0.0f : 1.0f);
3533 mPointerSimple.currentProperties.id = 0;
3534 mPointerSimple.currentProperties.toolType =
3535 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3536 } else {
3537 mPointerVelocityControl.reset();
3538
3539 down = false;
3540 hovering = false;
3541 }
3542
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003543 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003544}
3545
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003546std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3547 uint32_t policyFlags) {
3548 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003549
3550 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003551
3552 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003553}
3554
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003555std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3556 uint32_t policyFlags, bool down,
3557 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003558 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3559 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003560 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003561 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003562
3563 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003564 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003565 mPointerController->clearSpots();
Michael Wrightca5bede2020-07-02 00:00:29 +01003566 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003567 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003568 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003569 }
Garfield Tan9514d782020-11-10 16:37:23 -08003570 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003571
Prabir Pradhan2719e822023-02-28 17:39:36 +00003572 const auto [xCursorPosition, yCursorPosition] = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003573
3574 if (mPointerSimple.down && !down) {
3575 mPointerSimple.down = false;
3576
3577 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003578 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3579 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3580 0, metaState, mLastRawState.buttonState,
3581 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3582 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3583 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3584 yCursorPosition, mPointerSimple.downTime,
3585 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003586 }
3587
3588 if (mPointerSimple.hovering && !hovering) {
3589 mPointerSimple.hovering = false;
3590
3591 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003592 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3593 mSource, displayId, policyFlags,
3594 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3595 mLastRawState.buttonState, MotionClassification::NONE,
3596 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3597 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3598 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3599 yCursorPosition, mPointerSimple.downTime,
3600 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003601 }
3602
3603 if (down) {
3604 if (!mPointerSimple.down) {
3605 mPointerSimple.down = true;
3606 mPointerSimple.downTime = when;
3607
3608 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003609 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3610 mSource, displayId, policyFlags,
3611 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3612 mCurrentRawState.buttonState, MotionClassification::NONE,
3613 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3614 &mPointerSimple.currentProperties,
3615 &mPointerSimple.currentCoords, mOrientedXPrecision,
3616 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3617 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003618 }
3619
3620 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003621 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3622 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3623 0, 0, metaState, mCurrentRawState.buttonState,
3624 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3625 &mPointerSimple.currentProperties,
3626 &mPointerSimple.currentCoords, mOrientedXPrecision,
3627 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3628 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003629 }
3630
3631 if (hovering) {
3632 if (!mPointerSimple.hovering) {
3633 mPointerSimple.hovering = true;
3634
3635 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003636 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3637 mSource, displayId, policyFlags,
3638 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3639 mCurrentRawState.buttonState, MotionClassification::NONE,
3640 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3641 &mPointerSimple.currentProperties,
3642 &mPointerSimple.currentCoords, mOrientedXPrecision,
3643 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3644 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003645 }
3646
3647 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003648 out.push_back(
3649 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3650 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3651 metaState, mCurrentRawState.buttonState,
3652 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3653 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3654 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3655 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003656 }
3657
3658 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3659 float vscroll = mCurrentRawState.rawVScroll;
3660 float hscroll = mCurrentRawState.rawHScroll;
3661 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3662 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3663
3664 // Send scroll.
3665 PointerCoords pointerCoords;
3666 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3667 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3668 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3669
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003670 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3671 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3672 0, 0, metaState, mCurrentRawState.buttonState,
3673 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3674 &mPointerSimple.currentProperties, &pointerCoords,
3675 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3676 yCursorPosition, mPointerSimple.downTime,
3677 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003678 }
3679
3680 // Save state.
3681 if (down || hovering) {
3682 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3683 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003684 mPointerSimple.displayId = displayId;
3685 mPointerSimple.source = mSource;
3686 mPointerSimple.lastCursorX = xCursorPosition;
3687 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003688 } else {
3689 mPointerSimple.reset();
3690 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003691 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003692}
3693
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003694std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3695 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003696 std::list<NotifyArgs> out;
3697 if (mPointerSimple.down || mPointerSimple.hovering) {
3698 int32_t metaState = getContext()->getGlobalMetaState();
3699 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3700 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3701 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3702 metaState, mLastRawState.buttonState,
3703 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3704 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3705 mOrientedXPrecision, mOrientedYPrecision,
3706 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3707 mPointerSimple.downTime,
3708 /* videoFrames */ {}));
3709 if (mPointerController != nullptr) {
3710 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3711 }
3712 }
3713 mPointerSimple.reset();
3714 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003715}
3716
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003717static bool isStylusEvent(uint32_t source, int32_t action, const PointerProperties* properties) {
3718 if (!isFromSource(source, AINPUT_SOURCE_STYLUS)) {
3719 return false;
3720 }
3721 const auto actionIndex = action >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3722 return isStylusToolType(properties[actionIndex].toolType);
3723}
3724
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003725NotifyMotionArgs TouchInputMapper::dispatchMotion(
3726 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3727 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003728 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3729 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003730 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003731 PointerCoords pointerCoords[MAX_POINTERS];
3732 PointerProperties pointerProperties[MAX_POINTERS];
3733 uint32_t pointerCount = 0;
3734 while (!idBits.isEmpty()) {
3735 uint32_t id = idBits.clearFirstMarkedBit();
3736 uint32_t index = idToIndex[id];
3737 pointerProperties[pointerCount].copyFrom(properties[index]);
3738 pointerCoords[pointerCount].copyFrom(coords[index]);
3739
3740 if (changedId >= 0 && id == uint32_t(changedId)) {
3741 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3742 }
3743
3744 pointerCount += 1;
3745 }
3746
3747 ALOG_ASSERT(pointerCount != 0);
3748
3749 if (changedId >= 0 && pointerCount == 1) {
3750 // Replace initial down and final up action.
3751 // We can compare the action without masking off the changed pointer index
3752 // because we know the index is 0.
3753 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3754 action = AMOTION_EVENT_ACTION_DOWN;
3755 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003756 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3757 action = AMOTION_EVENT_ACTION_CANCEL;
3758 } else {
3759 action = AMOTION_EVENT_ACTION_UP;
3760 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003761 } else {
3762 // Can't happen.
3763 ALOG_ASSERT(false);
3764 }
3765 }
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003766
3767 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3768 const bool showDirectStylusPointer = mConfig.stylusPointerIconEnabled &&
3769 mDeviceMode == DeviceMode::DIRECT && isStylusEvent(source, action, pointerProperties) &&
Seunghwan Choi356026c2023-02-01 14:37:25 +09003770 mPointerController && displayId != ADISPLAY_ID_NONE &&
3771 displayId == mPointerController->getDisplayId();
Seunghwan Choi2de48e42023-01-17 20:45:15 +09003772 if (showDirectStylusPointer) {
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003773 switch (action & AMOTION_EVENT_ACTION_MASK) {
3774 case AMOTION_EVENT_ACTION_HOVER_ENTER:
3775 case AMOTION_EVENT_ACTION_HOVER_MOVE:
3776 mPointerController->setPresentation(
Seunghwan Choi75789cd2023-01-13 20:31:59 +09003777 PointerControllerInterface::Presentation::STYLUS_HOVER);
Seunghwan Choi032c7dc2023-01-12 16:03:47 +09003778 mPointerController
3779 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[0].getX(),
3780 mCurrentCookedState.cookedPointerData.pointerCoords[0]
3781 .getY());
3782 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
3783 break;
3784 case AMOTION_EVENT_ACTION_HOVER_EXIT:
3785 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
3786 break;
3787 }
3788 }
3789
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003790 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3791 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003792 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2719e822023-02-28 17:39:36 +00003793 std::tie(xCursorPosition, yCursorPosition) = mPointerController->getPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003794 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003795 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003796 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003797 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003798 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003799 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3800 policyFlags, action, actionButton, flags, metaState, buttonState,
3801 classification, edgeFlags, pointerCount, pointerProperties,
3802 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3803 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003804}
3805
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003806std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3807 std::list<NotifyArgs> out;
Harry Cutts33476232023-01-30 19:57:29 +00003808 out += abortPointerUsage(when, readTime, /*policyFlags=*/0);
3809 out += abortTouches(when, readTime, /* policyFlags=*/0);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003810 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003811}
3812
Prabir Pradhan1728b212021-10-19 16:00:03 -07003813bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003814 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003815 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003816 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003817}
3818
3819const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3820 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003821 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3822 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3823 "left=%d, top=%d, right=%d, bottom=%d",
3824 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3825 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003826
3827 if (virtualKey.isHit(x, y)) {
3828 return &virtualKey;
3829 }
3830 }
3831
3832 return nullptr;
3833}
3834
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003835void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3836 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3837 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003838
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003839 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003840
3841 if (currentPointerCount == 0) {
3842 // No pointers to assign.
3843 return;
3844 }
3845
3846 if (lastPointerCount == 0) {
3847 // All pointers are new.
3848 for (uint32_t i = 0; i < currentPointerCount; i++) {
3849 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003850 current.rawPointerData.pointers[i].id = id;
3851 current.rawPointerData.idToIndex[id] = i;
3852 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003853 }
3854 return;
3855 }
3856
3857 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003858 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003859 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003860 uint32_t id = last.rawPointerData.pointers[0].id;
3861 current.rawPointerData.pointers[0].id = id;
3862 current.rawPointerData.idToIndex[id] = 0;
3863 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003864 return;
3865 }
3866
3867 // General case.
3868 // We build a heap of squared euclidean distances between current and last pointers
3869 // associated with the current and last pointer indices. Then, we find the best
3870 // match (by distance) for each current pointer.
3871 // The pointers must have the same tool type but it is possible for them to
3872 // transition from hovering to touching or vice-versa while retaining the same id.
3873 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3874
3875 uint32_t heapSize = 0;
3876 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3877 currentPointerIndex++) {
3878 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3879 lastPointerIndex++) {
3880 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003881 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003882 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003883 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003884 if (currentPointer.toolType == lastPointer.toolType) {
3885 int64_t deltaX = currentPointer.x - lastPointer.x;
3886 int64_t deltaY = currentPointer.y - lastPointer.y;
3887
3888 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3889
3890 // Insert new element into the heap (sift up).
3891 heap[heapSize].currentPointerIndex = currentPointerIndex;
3892 heap[heapSize].lastPointerIndex = lastPointerIndex;
3893 heap[heapSize].distance = distance;
3894 heapSize += 1;
3895 }
3896 }
3897 }
3898
3899 // Heapify
3900 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3901 startIndex -= 1;
3902 for (uint32_t parentIndex = startIndex;;) {
3903 uint32_t childIndex = parentIndex * 2 + 1;
3904 if (childIndex >= heapSize) {
3905 break;
3906 }
3907
3908 if (childIndex + 1 < heapSize &&
3909 heap[childIndex + 1].distance < heap[childIndex].distance) {
3910 childIndex += 1;
3911 }
3912
3913 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3914 break;
3915 }
3916
3917 swap(heap[parentIndex], heap[childIndex]);
3918 parentIndex = childIndex;
3919 }
3920 }
3921
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003922 if (DEBUG_POINTER_ASSIGNMENT) {
3923 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3924 for (size_t i = 0; i < heapSize; i++) {
3925 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3926 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3927 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003928 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003929
3930 // Pull matches out by increasing order of distance.
3931 // To avoid reassigning pointers that have already been matched, the loop keeps track
3932 // of which last and current pointers have been matched using the matchedXXXBits variables.
3933 // It also tracks the used pointer id bits.
3934 BitSet32 matchedLastBits(0);
3935 BitSet32 matchedCurrentBits(0);
3936 BitSet32 usedIdBits(0);
3937 bool first = true;
3938 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3939 while (heapSize > 0) {
3940 if (first) {
3941 // The first time through the loop, we just consume the root element of
3942 // the heap (the one with smallest distance).
3943 first = false;
3944 } else {
3945 // Previous iterations consumed the root element of the heap.
3946 // Pop root element off of the heap (sift down).
3947 heap[0] = heap[heapSize];
3948 for (uint32_t parentIndex = 0;;) {
3949 uint32_t childIndex = parentIndex * 2 + 1;
3950 if (childIndex >= heapSize) {
3951 break;
3952 }
3953
3954 if (childIndex + 1 < heapSize &&
3955 heap[childIndex + 1].distance < heap[childIndex].distance) {
3956 childIndex += 1;
3957 }
3958
3959 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3960 break;
3961 }
3962
3963 swap(heap[parentIndex], heap[childIndex]);
3964 parentIndex = childIndex;
3965 }
3966
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003967 if (DEBUG_POINTER_ASSIGNMENT) {
3968 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3969 for (size_t j = 0; j < heapSize; j++) {
3970 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3971 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3972 heap[j].distance);
3973 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003974 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003975 }
3976
3977 heapSize -= 1;
3978
3979 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3980 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3981
3982 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3983 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3984
3985 matchedCurrentBits.markBit(currentPointerIndex);
3986 matchedLastBits.markBit(lastPointerIndex);
3987
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003988 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3989 current.rawPointerData.pointers[currentPointerIndex].id = id;
3990 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3991 current.rawPointerData.markIdBit(id,
3992 current.rawPointerData.isHovering(
3993 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003994 usedIdBits.markBit(id);
3995
Harry Cutts45483602022-08-24 14:36:48 +00003996 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3997 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3998 ", distance=%" PRIu64,
3999 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004000 break;
4001 }
4002 }
4003
4004 // Assign fresh ids to pointers that were not matched in the process.
4005 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4006 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4007 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4008
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004009 current.rawPointerData.pointers[currentPointerIndex].id = id;
4010 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4011 current.rawPointerData.markIdBit(id,
4012 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004013
Harry Cutts45483602022-08-24 14:36:48 +00004014 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4015 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4016 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004017 }
4018}
4019
4020int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4021 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4022 return AKEY_STATE_VIRTUAL;
4023 }
4024
4025 for (const VirtualKey& virtualKey : mVirtualKeys) {
4026 if (virtualKey.keyCode == keyCode) {
4027 return AKEY_STATE_UP;
4028 }
4029 }
4030
4031 return AKEY_STATE_UNKNOWN;
4032}
4033
4034int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4035 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4036 return AKEY_STATE_VIRTUAL;
4037 }
4038
4039 for (const VirtualKey& virtualKey : mVirtualKeys) {
4040 if (virtualKey.scanCode == scanCode) {
4041 return AKEY_STATE_UP;
4042 }
4043 }
4044
4045 return AKEY_STATE_UNKNOWN;
4046}
4047
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004048bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4049 const std::vector<int32_t>& keyCodes,
4050 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004051 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004052 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004053 if (virtualKey.keyCode == keyCodes[i]) {
4054 outFlags[i] = 1;
4055 }
4056 }
4057 }
4058
4059 return true;
4060}
4061
4062std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4063 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004064 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004065 return std::make_optional(mPointerController->getDisplayId());
4066 } else {
4067 return std::make_optional(mViewport.displayId);
4068 }
4069 }
4070 return std::nullopt;
4071}
4072
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004073} // namespace android