blob: 31287a3a78b5376175fde0da229764ae78e50bb3 [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Michael Wright227c5542020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wright227c5542020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
21#include "TouchInputMapper.h"
22
Dominik Laskowski75788452021-02-09 18:51:25 -080023#include <ftl/enum.h>
Prabir Pradhan8d9ba912022-11-11 22:26:33 +000024#include <input/PrintTools.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080025
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070026#include "CursorButtonAccumulator.h"
27#include "CursorScrollAccumulator.h"
28#include "TouchButtonAccumulator.h"
29#include "TouchCursorInputMapperCommon.h"
Michael Wrighta9cf4192022-12-01 23:46:39 +000030#include "ui/Rotation.h"
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070031
32namespace android {
33
34// --- Constants ---
35
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070036// Artificial latency on synthetic events created from stylus data without corresponding touch
37// data.
38static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
39
HQ Liue6983c72022-04-19 22:14:56 +000040// Minimum width between two pointers to determine a gesture as freeform gesture in mm
41static const float MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER = 30;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070042// --- Static Definitions ---
43
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +000044static const DisplayViewport kUninitializedViewport;
45
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000046static std::string toString(const Rect& rect) {
47 return base::StringPrintf("Rect{%d, %d, %d, %d}", rect.left, rect.top, rect.right, rect.bottom);
48}
49
50static std::string toString(const ui::Size& size) {
51 return base::StringPrintf("%dx%d", size.width, size.height);
52}
53
Prabir Pradhan675f25a2022-11-10 22:04:07 +000054static bool isPointInRect(const Rect& rect, vec2 p) {
55 return p.x >= rect.left && p.x < rect.right && p.y >= rect.top && p.y < rect.bottom;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000056}
57
Prabir Pradhane04ffaa2022-12-13 23:04:04 +000058static std::string toString(const InputDeviceUsiVersion& v) {
59 return base::StringPrintf("%d.%d", v.majorVersion, v.minorVersion);
60}
61
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070062template <typename T>
63inline static void swap(T& a, T& b) {
64 T temp = a;
65 a = b;
66 b = temp;
67}
68
69static float calculateCommonVector(float a, float b) {
70 if (a > 0 && b > 0) {
71 return a < b ? a : b;
72 } else if (a < 0 && b < 0) {
73 return a > b ? a : b;
74 } else {
75 return 0;
76 }
77}
78
79inline static float distance(float x1, float y1, float x2, float y2) {
80 return hypotf(x1 - x2, y1 - y2);
81}
82
83inline static int32_t signExtendNybble(int32_t value) {
84 return value >= 8 ? value - 16 : value;
85}
86
Prabir Pradhan675f25a2022-11-10 22:04:07 +000087static ui::Size getNaturalDisplaySize(const DisplayViewport& viewport) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000088 ui::Size rotatedDisplaySize{viewport.deviceWidth, viewport.deviceHeight};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +000089 if (viewport.orientation == ui::ROTATION_90 || viewport.orientation == ui::ROTATION_270) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000090 std::swap(rotatedDisplaySize.width, rotatedDisplaySize.height);
91 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +000092 return rotatedDisplaySize;
Prabir Pradhan2d613f42022-11-10 20:22:06 +000093}
94
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +000095static int32_t filterButtonState(InputReaderConfiguration& config, int32_t buttonState) {
96 if (!config.stylusButtonMotionEventsEnabled) {
97 buttonState &=
98 ~(AMOTION_EVENT_BUTTON_STYLUS_PRIMARY | AMOTION_EVENT_BUTTON_STYLUS_SECONDARY);
99 }
100 return buttonState;
101}
102
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700103// --- RawPointerData ---
104
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700105void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
106 float x = 0, y = 0;
107 uint32_t count = touchingIdBits.count();
108 if (count) {
109 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
110 uint32_t id = idBits.clearFirstMarkedBit();
111 const Pointer& pointer = pointerForId(id);
112 x += pointer.x;
113 y += pointer.y;
114 }
115 x /= count;
116 y /= count;
117 }
118 *outX = x;
119 *outY = y;
120}
121
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700122// --- TouchInputMapper ---
123
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800124TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
125 : InputMapper(deviceContext),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000126 mTouchButtonAccumulator(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700127 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100128 mDeviceMode(DeviceMode::DISABLED),
Michael Wrighta9cf4192022-12-01 23:46:39 +0000129 mInputDeviceOrientation(ui::ROTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700130
131TouchInputMapper::~TouchInputMapper() {}
132
Philip Junker4af3b3d2021-12-14 10:36:55 +0100133uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700134 return mSource;
135}
136
137void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
138 InputMapper::populateDeviceInfo(info);
139
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000140 if (mDeviceMode == DeviceMode::DISABLED) {
141 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700142 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000143
144 info->addMotionRange(mOrientedRanges.x);
145 info->addMotionRange(mOrientedRanges.y);
146 info->addMotionRange(mOrientedRanges.pressure);
147
148 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
149 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
150 //
151 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
152 // motion, i.e. the hardware dimensions, as the finger could move completely across the
153 // touchpad in one sample cycle.
154 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
155 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
156 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
157 x.resolution);
158 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
159 y.resolution);
160 }
161
162 if (mOrientedRanges.size) {
163 info->addMotionRange(*mOrientedRanges.size);
164 }
165
166 if (mOrientedRanges.touchMajor) {
167 info->addMotionRange(*mOrientedRanges.touchMajor);
168 info->addMotionRange(*mOrientedRanges.touchMinor);
169 }
170
171 if (mOrientedRanges.toolMajor) {
172 info->addMotionRange(*mOrientedRanges.toolMajor);
173 info->addMotionRange(*mOrientedRanges.toolMinor);
174 }
175
176 if (mOrientedRanges.orientation) {
177 info->addMotionRange(*mOrientedRanges.orientation);
178 }
179
180 if (mOrientedRanges.distance) {
181 info->addMotionRange(*mOrientedRanges.distance);
182 }
183
184 if (mOrientedRanges.tilt) {
185 info->addMotionRange(*mOrientedRanges.tilt);
186 }
187
188 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
189 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
190 }
191 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
192 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
193 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000194 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000195 info->setUsiVersion(mParameters.usiVersion);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700196}
197
198void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700199 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800200 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700201 dumpParameters(dump);
202 dumpVirtualKeys(dump);
203 dumpRawPointerAxes(dump);
204 dumpCalibration(dump);
205 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700206 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700207
208 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000209 mRawToDisplay.dump(dump, "RawToDisplay Transform:", INDENT4);
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000210 mRawRotation.dump(dump, "RawRotation Transform:", INDENT4);
211 dump += StringPrintf(INDENT4 "OrientedXPrecision: %0.3f\n", mOrientedXPrecision);
212 dump += StringPrintf(INDENT4 "OrientedYPrecision: %0.3f\n", mOrientedYPrecision);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700213 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
214 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
215 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
216 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
217 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
218 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
219 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
220 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
221 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
222 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
223
224 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
225 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
226 mLastRawState.rawPointerData.pointerCount);
227 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
228 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
229 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
230 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
231 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
232 "toolType=%d, isHovering=%s\n",
233 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
234 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
235 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
236 pointer.distance, pointer.toolType, toString(pointer.isHovering));
237 }
238
239 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
240 mLastCookedState.buttonState);
241 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
242 mLastCookedState.cookedPointerData.pointerCount);
243 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
244 const PointerProperties& pointerProperties =
245 mLastCookedState.cookedPointerData.pointerProperties[i];
246 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000247 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
248 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
249 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700250 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
251 "toolType=%d, isHovering=%s\n",
252 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000253 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
254 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700255 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
256 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
257 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
258 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
259 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
260 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
261 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
262 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
263 pointerProperties.toolType,
264 toString(mLastCookedState.cookedPointerData.isHovering(i)));
265 }
266
267 dump += INDENT3 "Stylus Fusion:\n";
268 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
269 toString(mExternalStylusConnected));
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000270 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
271 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700272 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
273 mExternalStylusFusionTimeout);
Prabir Pradhan124ea442022-10-28 20:27:44 +0000274 dump += StringPrintf(INDENT4 " External Stylus Buttons Applied: 0x%08x",
275 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700276 dump += INDENT3 "External Stylus State:\n";
277 dumpStylusState(dump, mExternalStylusState);
278
Michael Wright227c5542020-07-02 18:30:52 +0100279 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700280 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
281 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
282 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
283 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
284 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
285 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
286 }
287}
288
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700289std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
290 const InputReaderConfiguration* config,
291 uint32_t changes) {
292 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700293
294 mConfig = *config;
295
296 if (!changes) { // first time only
297 // Configure basic parameters.
298 configureParameters();
299
300 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800301 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000302 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700303
304 // Configure absolute axis information.
305 configureRawPointerAxes();
306
307 // Prepare input device calibration.
308 parseCalibration();
309 resolveCalibration();
310 }
311
312 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
313 // Update location calibration to reflect current settings
314 updateAffineTransformation();
315 }
316
317 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
318 // Update pointer speed.
319 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
320 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
321 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
322 }
323
324 bool resetNeeded = false;
325 if (!changes ||
326 (changes &
327 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800328 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700329 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
330 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
331 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700332 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700333 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700334 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700335 }
336
337 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700338 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000339
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700340 // Send reset, unless this is the first time the device has been configured,
341 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000342 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700343 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700344 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700345}
346
347void TouchInputMapper::resolveExternalStylusPresence() {
348 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800349 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700350 mExternalStylusConnected = !devices.empty();
351
352 if (!mExternalStylusConnected) {
353 resetExternalStylus();
354 }
355}
356
357void TouchInputMapper::configureParameters() {
358 // Use the pointer presentation mode for devices that do not support distinct
359 // multitouch. The spot-based presentation relies on being able to accurately
360 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800361 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100362 ? Parameters::GestureMode::SINGLE_TOUCH
363 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700364
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700365 std::string gestureModeString;
366 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800367 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700368 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100369 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700370 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100371 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700372 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700373 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700374 }
375 }
376
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000377 configureDeviceType();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700378
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800379 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700380
Michael Wright227c5542020-07-02 18:30:52 +0100381 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700382 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800383 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700384
Michael Wrighta9cf4192022-12-01 23:46:39 +0000385 mParameters.orientation = ui::ROTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700386 std::string orientationString;
387 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700388 orientationString)) {
389 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
390 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
391 } else if (orientationString == "ORIENTATION_90") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000392 mParameters.orientation = ui::ROTATION_90;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700393 } else if (orientationString == "ORIENTATION_180") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000394 mParameters.orientation = ui::ROTATION_180;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700395 } else if (orientationString == "ORIENTATION_270") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000396 mParameters.orientation = ui::ROTATION_270;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700397 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700398 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700399 }
400 }
401
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700402 mParameters.hasAssociatedDisplay = false;
403 mParameters.associatedDisplayIsExternal = false;
404 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100405 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000406 mParameters.deviceType == Parameters::DeviceType::POINTER ||
407 (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
408 getDeviceContext().getAssociatedViewport())) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700409 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100410 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800411 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700412 std::string uniqueDisplayId;
413 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800414 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700415 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
416 }
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.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800425 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700426 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000427
Prabir Pradhane04ffaa2022-12-13 23:04:04 +0000428 InputDeviceUsiVersion usiVersion;
429 if (getDeviceContext().getConfiguration().tryGetProperty("touch.usiVersionMajor",
430 usiVersion.majorVersion) &&
431 getDeviceContext().getConfiguration().tryGetProperty("touch.usiVersionMinor",
432 usiVersion.minorVersion)) {
433 mParameters.usiVersion = usiVersion;
434 }
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700435
436 mParameters.enableForInactiveViewport = false;
437 getDeviceContext().getConfiguration().tryGetProperty("touch.enableForInactiveViewport",
438 mParameters.enableForInactiveViewport);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700439}
440
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000441void TouchInputMapper::configureDeviceType() {
442 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
443 // The device is a touch screen.
444 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
445 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
446 // The device is a pointing device like a track pad.
447 mParameters.deviceType = Parameters::DeviceType::POINTER;
448 } else {
449 // The device is a touch pad of unknown purpose.
450 mParameters.deviceType = Parameters::DeviceType::POINTER;
451 }
452
453 // Type association takes precedence over the device type found in the idc file.
454 std::string deviceTypeString = getDeviceContext().getDeviceTypeAssociation().value_or("");
455 if (deviceTypeString.empty()) {
456 getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType", deviceTypeString);
457 }
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
804 // Compute oriented precision, scales and ranges.
805 // Note that the maximum value reported is an inclusive maximum value so it is one
806 // unit less than the total width or height of the display.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000807 // TODO(b/20508709): Calculate the oriented ranges using the input device's raw frame.
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800808 switch (mInputDeviceOrientation) {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000809 case ui::ROTATION_90:
810 case ui::ROTATION_270:
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800811 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000812 mOrientedRanges.x.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800813 mOrientedRanges.x.flat = 0;
814 mOrientedRanges.x.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000815 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mRawToDisplay.getScaleY();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800816
817 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000818 mOrientedRanges.y.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800819 mOrientedRanges.y.flat = 0;
820 mOrientedRanges.y.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000821 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mRawToDisplay.getScaleX();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800822 break;
823
824 default:
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800825 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000826 mOrientedRanges.x.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800827 mOrientedRanges.x.flat = 0;
828 mOrientedRanges.x.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000829 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mRawToDisplay.getScaleX();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800830
831 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000832 mOrientedRanges.y.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800833 mOrientedRanges.y.flat = 0;
834 mOrientedRanges.y.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000835 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mRawToDisplay.getScaleY();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800836 break;
837 }
838}
839
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000840void TouchInputMapper::computeInputTransforms() {
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000841 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
842
843 ui::Size rotatedRawSize = rawSize;
844 if (mInputDeviceOrientation == ui::ROTATION_270 || mInputDeviceOrientation == ui::ROTATION_90) {
845 std::swap(rotatedRawSize.width, rotatedRawSize.height);
846 }
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000847 const auto rotationFlags = ui::Transform::toRotationFlags(-mInputDeviceOrientation);
848 mRawRotation = ui::Transform{rotationFlags};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000849
850 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
851 ui::Transform undoRawOffset;
852 undoRawOffset.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
853
854 // Step 2: Rotate the raw coordinates to the expected orientation.
855 ui::Transform rotate;
856 // When rotating raw coordinates, the raw size will be used as an offset.
857 // Account for the extra unit added to the raw range when the raw size was calculated.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000858 rotate.set(rotationFlags, rotatedRawSize.width - 1, rotatedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000859
860 // Step 3: Scale the raw coordinates to the display space.
861 ui::Transform scaleToDisplay;
862 const float xScale = static_cast<float>(mDisplayBounds.width) / rotatedRawSize.width;
863 const float yScale = static_cast<float>(mDisplayBounds.height) / rotatedRawSize.height;
864 scaleToDisplay.set(xScale, 0, 0, yScale);
865
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000866 mRawToDisplay = (scaleToDisplay * (rotate * undoRawOffset));
867
868 // Calculate the transform that takes raw coordinates to the rotated display space.
869 ui::Transform displayToRotatedDisplay;
870 displayToRotatedDisplay.set(ui::Transform::toRotationFlags(-mViewport.orientation),
871 mViewport.deviceWidth, mViewport.deviceHeight);
872 mRawToRotatedDisplay = displayToRotatedDisplay * mRawToDisplay;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000873}
874
Prabir Pradhan1728b212021-10-19 16:00:03 -0700875void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000876 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700877
878 resolveExternalStylusPresence();
879
880 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100881 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000882 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700883 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100884 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700885 if (hasStylus()) {
886 mSource |= AINPUT_SOURCE_STYLUS;
Harry Cutts16a24cc2022-10-26 15:22:19 +0000887 } else {
888 mSource |= AINPUT_SOURCE_TOUCHPAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700889 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800890 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700891 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100892 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700893 if (hasStylus()) {
894 mSource |= AINPUT_SOURCE_STYLUS;
895 }
896 if (hasExternalStylus()) {
897 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
898 }
Michael Wright227c5542020-07-02 18:30:52 +0100899 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700900 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100901 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700902 } else {
903 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100904 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700905 }
906
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000907 const std::optional<DisplayViewport> newViewportOpt = findViewport();
908
909 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700910 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
911 ALOGW("Touch device '%s' did not report support for X or Y axis! "
912 "The device will be inoperable.",
913 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100914 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000915 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700916 ALOGI("Touch device '%s' could not query the properties of its associated "
917 "display. The device will be inoperable until the display size "
918 "becomes available.",
919 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100920 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700921 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000922 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
923 getDeviceName().c_str(), getDeviceId());
924 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000925 }
926
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700927 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000928 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000929 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
930 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
931 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
932 const float rawMeanResolution =
933 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700934
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000935 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
936 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700937 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700938 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000939 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
940 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
941 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700942
Michael Wright227c5542020-07-02 18:30:52 +0100943 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000944 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700945
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000946 mDisplayBounds = getNaturalDisplaySize(mViewport);
947 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
948 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700949
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000950 // InputReader works in the un-rotated display coordinate space, so we don't need to do
951 // anything if the device is already orientation-aware. If the device is not
952 // orientation-aware, then we need to apply the inverse rotation of the display so that
953 // when the display rotation is applied later as a part of the per-window transform, we
954 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700955 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +0000956 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000957 : getInverseRotation(mViewport.orientation);
958 // For orientation-aware devices that work in the un-rotated coordinate space, the
959 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000960 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000961 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700962
963 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +0000964 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000965 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700966 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000967 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000968 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +0000969 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000970 mRawToDisplay.reset();
971 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000972 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700973 }
974 }
975
976 // If moving between pointer modes, need to reset some state.
977 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
978 if (deviceModeChanged) {
979 mOrientedRanges.clear();
980 }
981
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800982 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
983 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100984 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800985 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000986 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
987 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800988 if (mPointerController == nullptr) {
989 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700990 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000991 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800992 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
993 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700994 } else {
lilinnandef700b2022-06-17 19:32:01 +0800995 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
996 !mConfig.showTouches) {
997 mPointerController->clearSpots();
998 }
Michael Wright17db18e2020-06-26 20:51:44 +0100999 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001000 }
1001
Prabir Pradhan93a0f912021-04-21 13:47:42 -07001002 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001003 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001004 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001005 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001006 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001007
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001008 configureVirtualKeys();
1009
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001010 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001011
1012 // Location
1013 updateAffineTransformation();
1014
Michael Wright227c5542020-07-02 18:30:52 +01001015 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001016 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001017 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1018 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001019
1020 // Scale movements such that one whole swipe of the touch pad covers a
1021 // given area relative to the diagonal size of the display when no acceleration
1022 // is applied.
1023 // Assume that the touch pad has a square aspect ratio such that movements in
1024 // X and Y of the same number of raw units cover the same physical distance.
1025 mPointerXMovementScale =
1026 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1027 mPointerYMovementScale = mPointerXMovementScale;
1028
1029 // Scale zooms to cover a smaller range of the display than movements do.
1030 // This value determines the area around the pointer that is affected by freeform
1031 // pointer gestures.
1032 mPointerXZoomScale =
1033 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1034 mPointerYZoomScale = mPointerXZoomScale;
1035
HQ Liue6983c72022-04-19 22:14:56 +00001036 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1037 // axis is non positive value.
1038 const float minFreeformGestureWidth =
1039 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1040
1041 mPointerGestureMaxSwipeWidth =
1042 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1043 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001044 }
1045
1046 // Inform the dispatcher about the changes.
1047 *outResetNeeded = true;
1048 bumpGeneration();
1049 }
1050}
1051
Prabir Pradhan1728b212021-10-19 16:00:03 -07001052void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001053 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001054 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001055 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1056 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001057 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001058}
1059
1060void TouchInputMapper::configureVirtualKeys() {
1061 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001062 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001063
1064 mVirtualKeys.clear();
1065
1066 if (virtualKeyDefinitions.size() == 0) {
1067 return;
1068 }
1069
1070 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1071 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1072 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1073 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1074
1075 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1076 VirtualKey virtualKey;
1077
1078 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1079 int32_t keyCode;
1080 int32_t dummyKeyMetaState;
1081 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001082 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1083 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001084 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1085 continue; // drop the key
1086 }
1087
1088 virtualKey.keyCode = keyCode;
1089 virtualKey.flags = flags;
1090
1091 // convert the key definition's display coordinates into touch coordinates for a hit box
1092 int32_t halfWidth = virtualKeyDefinition.width / 2;
1093 int32_t halfHeight = virtualKeyDefinition.height / 2;
1094
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001095 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1096 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001097 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001098 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1099 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001100 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001101 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1102 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001103 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001104 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1105 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001106 touchScreenTop;
1107 mVirtualKeys.push_back(virtualKey);
1108 }
1109}
1110
1111void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1112 if (!mVirtualKeys.empty()) {
1113 dump += INDENT3 "Virtual Keys:\n";
1114
1115 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1116 const VirtualKey& virtualKey = mVirtualKeys[i];
1117 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1118 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1119 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1120 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1121 }
1122 }
1123}
1124
1125void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001126 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001127 Calibration& out = mCalibration;
1128
1129 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001130 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001131 std::string sizeCalibrationString;
1132 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001133 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001134 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001135 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001136 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001137 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001138 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001140 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001141 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001142 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001143 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001144 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 }
1146 }
1147
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001148 float sizeScale;
1149
1150 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1151 out.sizeScale = sizeScale;
1152 }
1153 float sizeBias;
1154 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1155 out.sizeBias = sizeBias;
1156 }
1157 bool sizeIsSummed;
1158 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1159 out.sizeIsSummed = sizeIsSummed;
1160 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001161
1162 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001163 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001164 std::string pressureCalibrationString;
1165 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001166 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001167 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001168 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001169 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 } else if (pressureCalibrationString != "default") {
1173 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001174 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001175 }
1176 }
1177
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001178 float pressureScale;
1179 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1180 out.pressureScale = pressureScale;
1181 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001182
1183 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001184 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001185 std::string orientationCalibrationString;
1186 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001187 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001188 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001189 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001190 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001191 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001192 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193 } else if (orientationCalibrationString != "default") {
1194 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001195 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001196 }
1197 }
1198
1199 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001201 std::string distanceCalibrationString;
1202 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001203 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001204 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001206 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001207 } else if (distanceCalibrationString != "default") {
1208 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001209 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001210 }
1211 }
1212
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001213 float distanceScale;
1214 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1215 out.distanceScale = distanceScale;
1216 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001217}
1218
1219void TouchInputMapper::resolveCalibration() {
1220 // Size
1221 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001222 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1223 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001224 }
1225 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001226 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001227 }
1228
1229 // Pressure
1230 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001231 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1232 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001233 }
1234 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001235 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001236 }
1237
1238 // Orientation
1239 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001240 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1241 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001242 }
1243 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001244 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001245 }
1246
1247 // Distance
1248 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001249 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1250 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001251 }
1252 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001253 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001254 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001255}
1256
1257void TouchInputMapper::dumpCalibration(std::string& dump) {
1258 dump += INDENT3 "Calibration:\n";
1259
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001260 dump += INDENT4 "touch.size.calibration: ";
1261 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001262
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001263 if (mCalibration.sizeScale) {
1264 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001265 }
1266
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001267 if (mCalibration.sizeBias) {
1268 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001269 }
1270
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001271 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001272 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001273 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001274 }
1275
1276 // Pressure
1277 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001278 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001279 dump += INDENT4 "touch.pressure.calibration: none\n";
1280 break;
Michael Wright227c5542020-07-02 18:30:52 +01001281 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001282 dump += INDENT4 "touch.pressure.calibration: physical\n";
1283 break;
Michael Wright227c5542020-07-02 18:30:52 +01001284 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001285 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1286 break;
1287 default:
1288 ALOG_ASSERT(false);
1289 }
1290
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001291 if (mCalibration.pressureScale) {
1292 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001293 }
1294
1295 // Orientation
1296 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001297 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 dump += INDENT4 "touch.orientation.calibration: none\n";
1299 break;
Michael Wright227c5542020-07-02 18:30:52 +01001300 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001301 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1302 break;
Michael Wright227c5542020-07-02 18:30:52 +01001303 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001304 dump += INDENT4 "touch.orientation.calibration: vector\n";
1305 break;
1306 default:
1307 ALOG_ASSERT(false);
1308 }
1309
1310 // Distance
1311 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001312 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001313 dump += INDENT4 "touch.distance.calibration: none\n";
1314 break;
Michael Wright227c5542020-07-02 18:30:52 +01001315 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001316 dump += INDENT4 "touch.distance.calibration: scaled\n";
1317 break;
1318 default:
1319 ALOG_ASSERT(false);
1320 }
1321
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001322 if (mCalibration.distanceScale) {
1323 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001324 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001325}
1326
1327void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1328 dump += INDENT3 "Affine Transformation:\n";
1329
1330 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1331 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1332 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1333 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1334 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1335 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1336}
1337
1338void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001339 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001340 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001341}
1342
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001343std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001344 std::list<NotifyArgs> out = cancelTouch(when, when);
1345 updateTouchSpots();
1346
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001347 mCursorButtonAccumulator.reset(getDeviceContext());
1348 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001349 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001350
1351 mPointerVelocityControl.reset();
1352 mWheelXVelocityControl.reset();
1353 mWheelYVelocityControl.reset();
1354
1355 mRawStatesPending.clear();
1356 mCurrentRawState.clear();
1357 mCurrentCookedState.clear();
1358 mLastRawState.clear();
1359 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001360 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001361 mSentHoverEnter = false;
1362 mHavePointerIds = false;
1363 mCurrentMotionAborted = false;
1364 mDownTime = 0;
1365
1366 mCurrentVirtualKey.down = false;
1367
1368 mPointerGesture.reset();
1369 mPointerSimple.reset();
1370 resetExternalStylus();
1371
1372 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001373 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001374 mPointerController->clearSpots();
1375 }
1376
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001377 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001378}
1379
1380void TouchInputMapper::resetExternalStylus() {
1381 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001382 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001383 mExternalStylusFusionTimeout = LLONG_MAX;
1384 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001385 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001386}
1387
1388void TouchInputMapper::clearStylusDataPendingFlags() {
1389 mExternalStylusDataPending = false;
1390 mExternalStylusFusionTimeout = LLONG_MAX;
1391}
1392
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001393std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001394 mCursorButtonAccumulator.process(rawEvent);
1395 mCursorScrollAccumulator.process(rawEvent);
1396 mTouchButtonAccumulator.process(rawEvent);
1397
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001398 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001399 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001400 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001401 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001402 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001403}
1404
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001405std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1406 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001407 if (mDeviceMode == DeviceMode::DISABLED) {
1408 // Only save the last pending state when the device is disabled.
1409 mRawStatesPending.clear();
1410 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001411 // Push a new state.
1412 mRawStatesPending.emplace_back();
1413
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001414 RawState& next = mRawStatesPending.back();
1415 next.clear();
1416 next.when = when;
1417 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001418
1419 // Sync button state.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001420 next.buttonState = filterButtonState(mConfig,
1421 mTouchButtonAccumulator.getButtonState() |
1422 mCursorButtonAccumulator.getButtonState());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001423
1424 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001425 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1426 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001427 mCursorScrollAccumulator.finishSync();
1428
1429 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001430 syncTouch(when, &next);
1431
1432 // The last RawState is the actually second to last, since we just added a new state
1433 const RawState& last =
1434 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001435
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001436 std::tie(next.when, next.readTime) =
1437 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1438 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001439
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001440 // Assign pointer ids.
1441 if (!mHavePointerIds) {
1442 assignPointerIds(last, next);
1443 }
1444
Harry Cutts45483602022-08-24 14:36:48 +00001445 ALOGD_IF(DEBUG_RAW_EVENTS,
1446 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1447 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1448 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1449 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1450 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1451 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001452
Arthur Hung9ad18942021-06-19 02:04:46 +00001453 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1454 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1455 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1456 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1457 next.rawPointerData.hoveringIdBits.value);
1458 }
1459
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001460 out += processRawTouches(false /*timeout*/);
1461 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001462}
1463
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001464std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1465 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001466 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001467 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001468 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001469 }
1470
1471 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1472 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1473 // touching the current state will only observe the events that have been dispatched to the
1474 // rest of the pipeline.
1475 const size_t N = mRawStatesPending.size();
1476 size_t count;
1477 for (count = 0; count < N; count++) {
1478 const RawState& next = mRawStatesPending[count];
1479
1480 // A failure to assign the stylus id means that we're waiting on stylus data
1481 // and so should defer the rest of the pipeline.
1482 if (assignExternalStylusId(next, timeout)) {
1483 break;
1484 }
1485
1486 // All ready to go.
1487 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001488 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001489 if (mCurrentRawState.when < mLastRawState.when) {
1490 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001491 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001492 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001493 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001494 }
1495 if (count != 0) {
1496 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1497 }
1498
1499 if (mExternalStylusDataPending) {
1500 if (timeout) {
1501 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1502 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001503 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001504 ALOGD_IF(DEBUG_STYLUS_FUSION,
1505 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001506 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001507 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001508 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1509 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1510 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1511 }
1512 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001513 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001514}
1515
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001516std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1517 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001518 // Always start with a clean state.
1519 mCurrentCookedState.clear();
1520
1521 // Apply stylus buttons to current raw state.
1522 applyExternalStylusButtonState(when);
1523
1524 // Handle policy on initial down or hover events.
1525 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1526 mCurrentRawState.rawPointerData.pointerCount != 0;
1527
1528 uint32_t policyFlags = 0;
1529 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1530 if (initialDown || buttonsPressed) {
1531 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001532 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001533 getContext()->fadePointer();
1534 }
1535
1536 if (mParameters.wake) {
1537 policyFlags |= POLICY_FLAG_WAKE;
1538 }
1539 }
1540
1541 // Consume raw off-screen touches before cooking pointer data.
1542 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001543 bool consumed;
1544 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1545 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001546 mCurrentRawState.rawPointerData.clear();
1547 }
1548
1549 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1550 // with cooked pointer data that has the same ids and indices as the raw data.
1551 // The following code can use either the raw or cooked data, as needed.
1552 cookPointerData();
1553
1554 // Apply stylus pressure to current cooked state.
1555 applyExternalStylusTouchState(when);
1556
1557 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001558 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1559 mSource, mViewport.displayId, policyFlags,
1560 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001561
1562 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001563 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001564 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1565 uint32_t id = idBits.clearFirstMarkedBit();
1566 const RawPointerData::Pointer& pointer =
1567 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001568 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001569 mCurrentCookedState.stylusIdBits.markBit(id);
1570 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1571 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1572 mCurrentCookedState.fingerIdBits.markBit(id);
1573 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1574 mCurrentCookedState.mouseIdBits.markBit(id);
1575 }
1576 }
1577 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1578 uint32_t id = idBits.clearFirstMarkedBit();
1579 const RawPointerData::Pointer& pointer =
1580 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001581 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001582 mCurrentCookedState.stylusIdBits.markBit(id);
1583 }
1584 }
1585
1586 // Stylus takes precedence over all tools, then mouse, then finger.
1587 PointerUsage pointerUsage = mPointerUsage;
1588 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1589 mCurrentCookedState.mouseIdBits.clear();
1590 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001591 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001592 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1593 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001594 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001595 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1596 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001597 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001598 }
1599
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001600 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001601 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001602 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001603 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001604 out += dispatchButtonRelease(when, readTime, policyFlags);
1605 out += dispatchHoverExit(when, readTime, policyFlags);
1606 out += dispatchTouches(when, readTime, policyFlags);
1607 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1608 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001609 }
1610
1611 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1612 mCurrentMotionAborted = false;
1613 }
1614 }
1615
1616 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001617 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1618 mSource, mViewport.displayId, policyFlags,
1619 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001620
1621 // Clear some transient state.
1622 mCurrentRawState.rawVScroll = 0;
1623 mCurrentRawState.rawHScroll = 0;
1624
1625 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001626 mLastRawState = mCurrentRawState;
1627 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001628 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001629}
1630
Garfield Tanc734e4f2021-01-15 20:01:39 -08001631void TouchInputMapper::updateTouchSpots() {
1632 if (!mConfig.showTouches || mPointerController == nullptr) {
1633 return;
1634 }
1635
1636 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1637 // clear touch spots.
1638 if (mDeviceMode != DeviceMode::DIRECT &&
1639 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1640 return;
1641 }
1642
1643 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1644 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1645
1646 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001647 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1648 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001649 mCurrentCookedState.cookedPointerData.touchingIdBits,
1650 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001651}
1652
1653bool TouchInputMapper::isTouchScreen() {
1654 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1655 mParameters.hasAssociatedDisplay;
1656}
1657
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001658void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001659 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1660 // If any of the external buttons are already pressed by the touch device, ignore them.
Prabir Pradhan7aa7ff02022-12-21 21:05:38 +00001661 const int32_t pressedButtons =
1662 filterButtonState(mConfig,
1663 ~mCurrentRawState.buttonState & mExternalStylusState.buttons);
Prabir Pradhan124ea442022-10-28 20:27:44 +00001664 const int32_t releasedButtons =
1665 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1666
1667 mCurrentRawState.buttonState |= pressedButtons;
1668 mCurrentRawState.buttonState &= ~releasedButtons;
1669
1670 mExternalStylusButtonsApplied |= pressedButtons;
1671 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001672 }
1673}
1674
1675void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1676 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1677 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001678 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1679 return;
1680 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001681
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001682 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1683 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1684 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1685 : 0.f;
1686 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1687 pressure = *mExternalStylusState.pressure;
1688 }
1689 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1690 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001691
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001692 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001693 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001694 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001695 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001696 }
1697}
1698
1699bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001700 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001701 return false;
1702 }
1703
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001704 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001705 if (mFusedStylusPointerId &&
1706 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001707 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001708 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001709 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001710 }
1711
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001712 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1713 state.rawPointerData.pointerCount != 0;
1714 if (!initialDown) {
1715 return false;
1716 }
1717
1718 if (!mExternalStylusState.pressure) {
1719 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1720 return false;
1721 }
1722
1723 if (*mExternalStylusState.pressure != 0.0f) {
1724 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1725 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1726 return false;
1727 }
1728
1729 if (timeout) {
1730 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1731 mFusedStylusPointerId.reset();
1732 mExternalStylusFusionTimeout = LLONG_MAX;
1733 return false;
1734 }
1735
1736 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1737 // being processed until we either get pressure data or timeout.
1738 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1739 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1740 }
1741 ALOGD_IF(DEBUG_STYLUS_FUSION,
1742 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1743 mExternalStylusFusionTimeout);
1744 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1745 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001746}
1747
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001748std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1749 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001750 if (mDeviceMode == DeviceMode::POINTER) {
1751 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001752 // Since this is a synthetic event, we can consider its latency to be zero
1753 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001754 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001755 }
Michael Wright227c5542020-07-02 18:30:52 +01001756 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001757 if (mExternalStylusFusionTimeout <= when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001758 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001759 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1760 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1761 }
1762 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001763 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001764}
1765
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001766std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1767 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001768 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001769 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001770 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001771 // The following three cases are handled here:
1772 // - We're in the middle of a fused stream of data;
1773 // - We're waiting on external stylus data before dispatching the initial down; or
1774 // - Only the button state, which is not reported through a specific pointer, has changed.
1775 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001776 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001777 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001778 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001779 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001780}
1781
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001782std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1783 uint32_t policyFlags, bool& outConsumed) {
1784 outConsumed = false;
1785 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001786 // Check for release of a virtual key.
1787 if (mCurrentVirtualKey.down) {
1788 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1789 // Pointer went up while virtual key was down.
1790 mCurrentVirtualKey.down = false;
1791 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001792 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1793 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1794 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001795 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1796 AKEY_EVENT_FLAG_FROM_SYSTEM |
1797 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001798 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001799 outConsumed = true;
1800 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001801 }
1802
1803 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1804 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1805 const RawPointerData::Pointer& pointer =
1806 mCurrentRawState.rawPointerData.pointerForId(id);
1807 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1808 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1809 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001810 outConsumed = true;
1811 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001812 }
1813 }
1814
1815 // Pointer left virtual key area or another pointer also went down.
1816 // Send key cancellation but do not consume the touch yet.
1817 // This is useful when the user swipes through from the virtual key area
1818 // into the main display surface.
1819 mCurrentVirtualKey.down = false;
1820 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001821 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1822 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001823 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1824 AKEY_EVENT_FLAG_FROM_SYSTEM |
1825 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1826 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001827 }
1828 }
1829
1830 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1831 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1832 // Pointer just went down. Check for virtual key press or off-screen touches.
1833 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1834 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001835 // Skip checking whether the pointer is inside the physical frame if the device is in
1836 // unscaled mode.
1837 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1838 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001839 // If exactly one pointer went down, check for virtual key hit.
1840 // Otherwise we will drop the entire stroke.
1841 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1842 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1843 if (virtualKey) {
1844 mCurrentVirtualKey.down = true;
1845 mCurrentVirtualKey.downTime = when;
1846 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1847 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1848 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001849 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1850 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001851
1852 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001853 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1854 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1855 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001856 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1857 AKEY_EVENT_ACTION_DOWN,
1858 AKEY_EVENT_FLAG_FROM_SYSTEM |
1859 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001860 }
1861 }
1862 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001863 outConsumed = true;
1864 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001865 }
1866 }
1867
1868 // Disable all virtual key touches that happen within a short time interval of the
1869 // most recent touch within the screen area. The idea is to filter out stray
1870 // virtual key presses when interacting with the touch screen.
1871 //
1872 // Problems we're trying to solve:
1873 //
1874 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1875 // virtual key area that is implemented by a separate touch panel and accidentally
1876 // triggers a virtual key.
1877 //
1878 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1879 // area and accidentally triggers a virtual key. This often happens when virtual keys
1880 // are layed out below the screen near to where the on screen keyboard's space bar
1881 // is displayed.
1882 if (mConfig.virtualKeyQuietTime > 0 &&
1883 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001884 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001885 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001886 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001887}
1888
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001889NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1890 uint32_t policyFlags, int32_t keyEventAction,
1891 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001892 int32_t keyCode = mCurrentVirtualKey.keyCode;
1893 int32_t scanCode = mCurrentVirtualKey.scanCode;
1894 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001895 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001896 policyFlags |= POLICY_FLAG_VIRTUAL;
1897
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001898 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1899 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1900 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001901}
1902
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001903std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1904 uint32_t policyFlags) {
1905 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001906 if (mCurrentMotionAborted) {
1907 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001908 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001909 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001910 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1911 if (!currentIdBits.isEmpty()) {
1912 int32_t metaState = getContext()->getGlobalMetaState();
1913 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001914 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001915 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1916 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001917 mCurrentCookedState.cookedPointerData.pointerProperties,
1918 mCurrentCookedState.cookedPointerData.pointerCoords,
1919 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1920 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1921 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001922 mCurrentMotionAborted = true;
1923 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001924 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001925}
1926
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001927// Updates pointer coords and properties for pointers with specified ids that have moved.
1928// Returns true if any of them changed.
1929static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1930 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1931 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1932 BitSet32 idBits) {
1933 bool changed = false;
1934 while (!idBits.isEmpty()) {
1935 uint32_t id = idBits.clearFirstMarkedBit();
1936 uint32_t inIndex = inIdToIndex[id];
1937 uint32_t outIndex = outIdToIndex[id];
1938
1939 const PointerProperties& curInProperties = inProperties[inIndex];
1940 const PointerCoords& curInCoords = inCoords[inIndex];
1941 PointerProperties& curOutProperties = outProperties[outIndex];
1942 PointerCoords& curOutCoords = outCoords[outIndex];
1943
1944 if (curInProperties != curOutProperties) {
1945 curOutProperties.copyFrom(curInProperties);
1946 changed = true;
1947 }
1948
1949 if (curInCoords != curOutCoords) {
1950 curOutCoords.copyFrom(curInCoords);
1951 changed = true;
1952 }
1953 }
1954 return changed;
1955}
1956
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001957std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1958 uint32_t policyFlags) {
1959 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001960 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1961 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1962 int32_t metaState = getContext()->getGlobalMetaState();
1963 int32_t buttonState = mCurrentCookedState.buttonState;
1964
1965 if (currentIdBits == lastIdBits) {
1966 if (!currentIdBits.isEmpty()) {
1967 // No pointer id changes so this is a move event.
1968 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001969 out.push_back(
1970 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1971 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1972 mCurrentCookedState.cookedPointerData.pointerProperties,
1973 mCurrentCookedState.cookedPointerData.pointerCoords,
1974 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1975 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1976 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001977 }
1978 } else {
1979 // There may be pointers going up and pointers going down and pointers moving
1980 // all at the same time.
1981 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1982 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1983 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1984 BitSet32 dispatchedIdBits(lastIdBits.value);
1985
1986 // Update last coordinates of pointers that have moved so that we observe the new
1987 // pointer positions at the same time as other pointers that have just gone up.
1988 bool moveNeeded =
1989 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1990 mCurrentCookedState.cookedPointerData.pointerCoords,
1991 mCurrentCookedState.cookedPointerData.idToIndex,
1992 mLastCookedState.cookedPointerData.pointerProperties,
1993 mLastCookedState.cookedPointerData.pointerCoords,
1994 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1995 if (buttonState != mLastCookedState.buttonState) {
1996 moveNeeded = true;
1997 }
1998
1999 // Dispatch pointer up events.
2000 while (!upIdBits.isEmpty()) {
2001 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002002 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002003 if (isCanceled) {
2004 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2005 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002006 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2007 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2008 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2009 buttonState, 0,
2010 mLastCookedState.cookedPointerData.pointerProperties,
2011 mLastCookedState.cookedPointerData.pointerCoords,
2012 mLastCookedState.cookedPointerData.idToIndex,
2013 dispatchedIdBits, upId, mOrientedXPrecision,
2014 mOrientedYPrecision, mDownTime,
2015 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002016 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002017 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002018 }
2019
2020 // Dispatch move events if any of the remaining pointers moved from their old locations.
2021 // Although applications receive new locations as part of individual pointer up
2022 // events, they do not generally handle them except when presented in a move event.
2023 if (moveNeeded && !moveIdBits.isEmpty()) {
2024 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002025 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2026 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2027 mCurrentCookedState.cookedPointerData.pointerProperties,
2028 mCurrentCookedState.cookedPointerData.pointerCoords,
2029 mCurrentCookedState.cookedPointerData.idToIndex,
2030 dispatchedIdBits, -1, mOrientedXPrecision,
2031 mOrientedYPrecision, mDownTime,
2032 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002033 }
2034
2035 // Dispatch pointer down events using the new pointer locations.
2036 while (!downIdBits.isEmpty()) {
2037 uint32_t downId = downIdBits.clearFirstMarkedBit();
2038 dispatchedIdBits.markBit(downId);
2039
2040 if (dispatchedIdBits.count() == 1) {
2041 // First pointer is going down. Set down time.
2042 mDownTime = when;
2043 }
2044
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002045 out.push_back(
2046 dispatchMotion(when, readTime, policyFlags, mSource,
2047 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2048 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2049 mCurrentCookedState.cookedPointerData.pointerCoords,
2050 mCurrentCookedState.cookedPointerData.idToIndex,
2051 dispatchedIdBits, downId, mOrientedXPrecision,
2052 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002053 }
2054 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002055 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002056}
2057
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002058std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2059 uint32_t policyFlags) {
2060 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002061 if (mSentHoverEnter &&
2062 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2063 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2064 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002065 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2066 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2067 mLastCookedState.buttonState, 0,
2068 mLastCookedState.cookedPointerData.pointerProperties,
2069 mLastCookedState.cookedPointerData.pointerCoords,
2070 mLastCookedState.cookedPointerData.idToIndex,
2071 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2072 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2073 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002074 mSentHoverEnter = false;
2075 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002076 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002077}
2078
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002079std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2080 uint32_t policyFlags) {
2081 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002082 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2083 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2084 int32_t metaState = getContext()->getGlobalMetaState();
2085 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002086 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2087 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2088 mCurrentRawState.buttonState, 0,
2089 mCurrentCookedState.cookedPointerData.pointerProperties,
2090 mCurrentCookedState.cookedPointerData.pointerCoords,
2091 mCurrentCookedState.cookedPointerData.idToIndex,
2092 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2093 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2094 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002095 mSentHoverEnter = true;
2096 }
2097
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002098 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2099 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2100 mCurrentRawState.buttonState, 0,
2101 mCurrentCookedState.cookedPointerData.pointerProperties,
2102 mCurrentCookedState.cookedPointerData.pointerCoords,
2103 mCurrentCookedState.cookedPointerData.idToIndex,
2104 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2105 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2106 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002107 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002108 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002109}
2110
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002111std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2112 uint32_t policyFlags) {
2113 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002114 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2115 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2116 const int32_t metaState = getContext()->getGlobalMetaState();
2117 int32_t buttonState = mLastCookedState.buttonState;
2118 while (!releasedButtons.isEmpty()) {
2119 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2120 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002121 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2122 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2123 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002124 mLastCookedState.cookedPointerData.pointerProperties,
2125 mLastCookedState.cookedPointerData.pointerCoords,
2126 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002127 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2128 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002129 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002130 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002131}
2132
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002133std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2134 uint32_t policyFlags) {
2135 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002136 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2137 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2138 const int32_t metaState = getContext()->getGlobalMetaState();
2139 int32_t buttonState = mLastCookedState.buttonState;
2140 while (!pressedButtons.isEmpty()) {
2141 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2142 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002143 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2144 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2145 buttonState, 0,
2146 mCurrentCookedState.cookedPointerData.pointerProperties,
2147 mCurrentCookedState.cookedPointerData.pointerCoords,
2148 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2149 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2150 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002151 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002152 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002153}
2154
2155const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2156 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2157 return cookedPointerData.touchingIdBits;
2158 }
2159 return cookedPointerData.hoveringIdBits;
2160}
2161
2162void TouchInputMapper::cookPointerData() {
2163 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2164
2165 mCurrentCookedState.cookedPointerData.clear();
2166 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2167 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2168 mCurrentRawState.rawPointerData.hoveringIdBits;
2169 mCurrentCookedState.cookedPointerData.touchingIdBits =
2170 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002171 mCurrentCookedState.cookedPointerData.canceledIdBits =
2172 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002173
2174 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2175 mCurrentCookedState.buttonState = 0;
2176 } else {
2177 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2178 }
2179
2180 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002181 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002182 for (uint32_t i = 0; i < currentPointerCount; i++) {
2183 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2184
2185 // Size
2186 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2187 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002188 case Calibration::SizeCalibration::GEOMETRIC:
2189 case Calibration::SizeCalibration::DIAMETER:
2190 case Calibration::SizeCalibration::BOX:
2191 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002192 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2193 touchMajor = in.touchMajor;
2194 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2195 toolMajor = in.toolMajor;
2196 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2197 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2198 : in.touchMajor;
2199 } else if (mRawPointerAxes.touchMajor.valid) {
2200 toolMajor = touchMajor = in.touchMajor;
2201 toolMinor = touchMinor =
2202 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2203 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2204 : in.touchMajor;
2205 } else if (mRawPointerAxes.toolMajor.valid) {
2206 touchMajor = toolMajor = in.toolMajor;
2207 touchMinor = toolMinor =
2208 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2209 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2210 : in.toolMajor;
2211 } else {
2212 ALOG_ASSERT(false,
2213 "No touch or tool axes. "
2214 "Size calibration should have been resolved to NONE.");
2215 touchMajor = 0;
2216 touchMinor = 0;
2217 toolMajor = 0;
2218 toolMinor = 0;
2219 size = 0;
2220 }
2221
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002222 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002223 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2224 if (touchingCount > 1) {
2225 touchMajor /= touchingCount;
2226 touchMinor /= touchingCount;
2227 toolMajor /= touchingCount;
2228 toolMinor /= touchingCount;
2229 size /= touchingCount;
2230 }
2231 }
2232
Michael Wright227c5542020-07-02 18:30:52 +01002233 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002234 touchMajor *= mGeometricScale;
2235 touchMinor *= mGeometricScale;
2236 toolMajor *= mGeometricScale;
2237 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002238 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002239 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2240 touchMinor = touchMajor;
2241 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2242 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002243 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002244 touchMinor = touchMajor;
2245 toolMinor = toolMajor;
2246 }
2247
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002248 mCalibration.applySizeScaleAndBias(touchMajor);
2249 mCalibration.applySizeScaleAndBias(touchMinor);
2250 mCalibration.applySizeScaleAndBias(toolMajor);
2251 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002252 size *= mSizeScale;
2253 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002254 case Calibration::SizeCalibration::DEFAULT:
2255 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2256 break;
2257 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002258 touchMajor = 0;
2259 touchMinor = 0;
2260 toolMajor = 0;
2261 toolMinor = 0;
2262 size = 0;
2263 break;
2264 }
2265
2266 // Pressure
2267 float pressure;
2268 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002269 case Calibration::PressureCalibration::PHYSICAL:
2270 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002271 pressure = in.pressure * mPressureScale;
2272 break;
2273 default:
2274 pressure = in.isHovering ? 0 : 1;
2275 break;
2276 }
2277
2278 // Tilt and Orientation
2279 float tilt;
2280 float orientation;
2281 if (mHaveTilt) {
2282 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2283 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002284 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002285 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2286 } else {
2287 tilt = 0;
2288
2289 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002290 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002291 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002292 break;
Michael Wright227c5542020-07-02 18:30:52 +01002293 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002294 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2295 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2296 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002297 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002298 float confidence = hypotf(c1, c2);
2299 float scale = 1.0f + confidence / 16.0f;
2300 touchMajor *= scale;
2301 touchMinor /= scale;
2302 toolMajor *= scale;
2303 toolMinor /= scale;
2304 } else {
2305 orientation = 0;
2306 }
2307 break;
2308 }
2309 default:
2310 orientation = 0;
2311 }
2312 }
2313
2314 // Distance
2315 float distance;
2316 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002317 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002318 distance = in.distance * mDistanceScale;
2319 break;
2320 default:
2321 distance = 0;
2322 }
2323
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002324 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2325 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002326 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2327 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002328
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002329 // Write output coords.
2330 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2331 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002332 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2333 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002334 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2335 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2336 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2337 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2338 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2339 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2340 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002341 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2342 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002343
Chris Ye364fdb52020-08-05 15:07:56 -07002344 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002345 uint32_t id = in.id;
2346 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2347 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2348 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002349 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2350 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002351 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2352 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2353 }
2354
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002355 // Write output properties.
2356 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002357 properties.clear();
2358 properties.id = id;
2359 properties.toolType = in.toolType;
2360
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002361 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002362 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002363 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002364 }
2365}
2366
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002367std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2368 uint32_t policyFlags,
2369 PointerUsage pointerUsage) {
2370 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002371 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002372 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002373 mPointerUsage = pointerUsage;
2374 }
2375
2376 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002377 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002378 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002379 break;
Michael Wright227c5542020-07-02 18:30:52 +01002380 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002381 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002382 break;
Michael Wright227c5542020-07-02 18:30:52 +01002383 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002384 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002385 break;
Michael Wright227c5542020-07-02 18:30:52 +01002386 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002387 break;
2388 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002389 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002390}
2391
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002392std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2393 uint32_t policyFlags) {
2394 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002395 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002396 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002397 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002398 break;
Michael Wright227c5542020-07-02 18:30:52 +01002399 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002400 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002401 break;
Michael Wright227c5542020-07-02 18:30:52 +01002402 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002403 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002404 break;
Michael Wright227c5542020-07-02 18:30:52 +01002405 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002406 break;
2407 }
2408
Michael Wright227c5542020-07-02 18:30:52 +01002409 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002410 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002411}
2412
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002413std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2414 uint32_t policyFlags,
2415 bool isTimeout) {
2416 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002417 // Update current gesture coordinates.
2418 bool cancelPreviousGesture, finishPreviousGesture;
2419 bool sendEvents =
2420 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2421 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002422 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002423 }
2424 if (finishPreviousGesture) {
2425 cancelPreviousGesture = false;
2426 }
2427
2428 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002429 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002430 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002431 if (finishPreviousGesture || cancelPreviousGesture) {
2432 mPointerController->clearSpots();
2433 }
2434
Michael Wright227c5542020-07-02 18:30:52 +01002435 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002436 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2437 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002438 mPointerGesture.currentGestureIdBits,
2439 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002440 }
2441 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002442 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002443 }
2444
2445 // Show or hide the pointer if needed.
2446 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002447 case PointerGesture::Mode::NEUTRAL:
2448 case PointerGesture::Mode::QUIET:
2449 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2450 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002451 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002452 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002453 }
2454 break;
Michael Wright227c5542020-07-02 18:30:52 +01002455 case PointerGesture::Mode::TAP:
2456 case PointerGesture::Mode::TAP_DRAG:
2457 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2458 case PointerGesture::Mode::HOVER:
2459 case PointerGesture::Mode::PRESS:
2460 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002461 // Unfade the pointer when the current gesture manipulates the
2462 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002463 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002464 break;
Michael Wright227c5542020-07-02 18:30:52 +01002465 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002466 // Fade the pointer when the current gesture manipulates a different
2467 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002468 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002469 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002470 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002471 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002472 }
2473 break;
2474 }
2475
2476 // Send events!
2477 int32_t metaState = getContext()->getGlobalMetaState();
2478 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002479 const MotionClassification classification =
2480 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2481 ? MotionClassification::TWO_FINGER_SWIPE
2482 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002483
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002484 uint32_t flags = 0;
2485
2486 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2487 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2488 }
2489
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002490 // Update last coordinates of pointers that have moved so that we observe the new
2491 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002492 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2493 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2494 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2495 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2496 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2497 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002498 bool moveNeeded = false;
2499 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2500 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2501 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2502 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2503 mPointerGesture.lastGestureIdBits.value);
2504 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2505 mPointerGesture.currentGestureCoords,
2506 mPointerGesture.currentGestureIdToIndex,
2507 mPointerGesture.lastGestureProperties,
2508 mPointerGesture.lastGestureCoords,
2509 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2510 if (buttonState != mLastCookedState.buttonState) {
2511 moveNeeded = true;
2512 }
2513 }
2514
2515 // Send motion events for all pointers that went up or were canceled.
2516 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2517 if (!dispatchedGestureIdBits.isEmpty()) {
2518 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002519 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002520 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002521 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002522 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2523 mPointerGesture.lastGestureProperties,
2524 mPointerGesture.lastGestureCoords,
2525 mPointerGesture.lastGestureIdToIndex,
2526 dispatchedGestureIdBits, -1, 0, 0,
2527 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002528
2529 dispatchedGestureIdBits.clear();
2530 } else {
2531 BitSet32 upGestureIdBits;
2532 if (finishPreviousGesture) {
2533 upGestureIdBits = dispatchedGestureIdBits;
2534 } else {
2535 upGestureIdBits.value =
2536 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2537 }
2538 while (!upGestureIdBits.isEmpty()) {
2539 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2540
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002541 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2542 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2543 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2544 mPointerGesture.lastGestureProperties,
2545 mPointerGesture.lastGestureCoords,
2546 mPointerGesture.lastGestureIdToIndex,
2547 dispatchedGestureIdBits, id, 0, 0,
2548 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002549
2550 dispatchedGestureIdBits.clearBit(id);
2551 }
2552 }
2553 }
2554
2555 // Send motion events for all pointers that moved.
2556 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002557 out.push_back(
2558 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2559 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2560 mPointerGesture.currentGestureProperties,
2561 mPointerGesture.currentGestureCoords,
2562 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2563 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002564 }
2565
2566 // Send motion events for all pointers that went down.
2567 if (down) {
2568 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2569 ~dispatchedGestureIdBits.value);
2570 while (!downGestureIdBits.isEmpty()) {
2571 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2572 dispatchedGestureIdBits.markBit(id);
2573
2574 if (dispatchedGestureIdBits.count() == 1) {
2575 mPointerGesture.downTime = when;
2576 }
2577
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002578 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2579 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2580 buttonState, 0, mPointerGesture.currentGestureProperties,
2581 mPointerGesture.currentGestureCoords,
2582 mPointerGesture.currentGestureIdToIndex,
2583 dispatchedGestureIdBits, id, 0, 0,
2584 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002585 }
2586 }
2587
2588 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002589 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002590 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2591 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2592 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2593 mPointerGesture.currentGestureProperties,
2594 mPointerGesture.currentGestureCoords,
2595 mPointerGesture.currentGestureIdToIndex,
2596 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2597 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002598 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2599 // Synthesize a hover move event after all pointers go up to indicate that
2600 // the pointer is hovering again even if the user is not currently touching
2601 // the touch pad. This ensures that a view will receive a fresh hover enter
2602 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002603 float x, y;
2604 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002605
2606 PointerProperties pointerProperties;
2607 pointerProperties.clear();
2608 pointerProperties.id = 0;
2609 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2610
2611 PointerCoords pointerCoords;
2612 pointerCoords.clear();
2613 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2614 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2615
2616 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002617 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2618 mSource, displayId, policyFlags,
2619 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2620 buttonState, MotionClassification::NONE,
2621 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2622 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2623 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002624 }
2625
2626 // Update state.
2627 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2628 if (!down) {
2629 mPointerGesture.lastGestureIdBits.clear();
2630 } else {
2631 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2632 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2633 uint32_t id = idBits.clearFirstMarkedBit();
2634 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2635 mPointerGesture.lastGestureProperties[index].copyFrom(
2636 mPointerGesture.currentGestureProperties[index]);
2637 mPointerGesture.lastGestureCoords[index].copyFrom(
2638 mPointerGesture.currentGestureCoords[index]);
2639 mPointerGesture.lastGestureIdToIndex[id] = index;
2640 }
2641 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002642 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002643}
2644
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002645std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2646 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002647 const MotionClassification classification =
2648 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2649 ? MotionClassification::TWO_FINGER_SWIPE
2650 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002651 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002652 // Cancel previously dispatches pointers.
2653 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2654 int32_t metaState = getContext()->getGlobalMetaState();
2655 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002656 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002657 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2658 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002659 mPointerGesture.lastGestureProperties,
2660 mPointerGesture.lastGestureCoords,
2661 mPointerGesture.lastGestureIdToIndex,
2662 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2663 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002664 }
2665
2666 // Reset the current pointer gesture.
2667 mPointerGesture.reset();
2668 mPointerVelocityControl.reset();
2669
2670 // Remove any current spots.
2671 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002672 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002673 mPointerController->clearSpots();
2674 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002675 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002676}
2677
2678bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2679 bool* outFinishPreviousGesture, bool isTimeout) {
2680 *outCancelPreviousGesture = false;
2681 *outFinishPreviousGesture = false;
2682
2683 // Handle TAP timeout.
2684 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002685 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002686
Michael Wright227c5542020-07-02 18:30:52 +01002687 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002688 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2689 // The tap/drag timeout has not yet expired.
2690 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2691 mConfig.pointerGestureTapDragInterval);
2692 } else {
2693 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002694 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002695 *outFinishPreviousGesture = true;
2696
2697 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002698 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002699 mPointerGesture.currentGestureIdBits.clear();
2700
2701 mPointerVelocityControl.reset();
2702 return true;
2703 }
2704 }
2705
2706 // We did not handle this timeout.
2707 return false;
2708 }
2709
2710 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2711 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2712
2713 // Update the velocity tracker.
2714 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002715 std::vector<float> positionsX;
2716 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002717 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002718 uint32_t id = idBits.clearFirstMarkedBit();
2719 const RawPointerData::Pointer& pointer =
2720 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002721 positionsX.push_back(pointer.x * mPointerXMovementScale);
2722 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002723 }
2724 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002725 {{AMOTION_EVENT_AXIS_X, positionsX},
2726 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002727 }
2728
2729 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2730 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002731 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2732 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2733 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002734 mPointerGesture.resetTap();
2735 }
2736
2737 // Pick a new active touch id if needed.
2738 // Choose an arbitrary pointer that just went down, if there is one.
2739 // Otherwise choose an arbitrary remaining pointer.
2740 // This guarantees we always have an active touch id when there is at least one pointer.
2741 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002742 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002743 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002744 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002745 mPointerGesture.firstTouchTime = when;
2746 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002747 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2748 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2749 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2750 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002751 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002752 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002753
2754 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002755 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002756 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002757 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2758 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2759 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002760 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002761 *outFinishPreviousGesture = true;
2762 }
2763
2764 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002765 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002766 mPointerGesture.currentGestureIdBits.clear();
2767
2768 mPointerVelocityControl.reset();
2769 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2770 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2771 // The pointer follows the active touch point.
2772 // Emit DOWN, MOVE, UP events at the pointer location.
2773 //
2774 // Only the active touch matters; other fingers are ignored. This policy helps
2775 // to handle the case where the user places a second finger on the touch pad
2776 // to apply the necessary force to depress an integrated button below the surface.
2777 // We don't want the second finger to be delivered to applications.
2778 //
2779 // For this to work well, we need to make sure to track the pointer that is really
2780 // active. If the user first puts one finger down to click then adds another
2781 // finger to drag then the active pointer should switch to the finger that is
2782 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002783 ALOGD_IF(DEBUG_GESTURES,
2784 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2785 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002786 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002787 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002788 *outFinishPreviousGesture = true;
2789 mPointerGesture.activeGestureId = 0;
2790 }
2791
2792 // Switch pointers if needed.
2793 // Find the fastest pointer and follow it.
2794 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002795 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002796 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002797 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002798 ALOGD_IF(DEBUG_GESTURES,
2799 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2800 "bestSpeed=%0.3f",
2801 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002802 }
2803 }
2804
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002805 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002806 // When using spots, the click will occur at the position of the anchor
2807 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002808 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002809 } else {
2810 mPointerVelocityControl.reset();
2811 }
2812
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002813 float x, y;
2814 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002815
Michael Wright227c5542020-07-02 18:30:52 +01002816 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002817 mPointerGesture.currentGestureIdBits.clear();
2818 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2819 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2820 mPointerGesture.currentGestureProperties[0].clear();
2821 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2822 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2823 mPointerGesture.currentGestureCoords[0].clear();
2824 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2825 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2826 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2827 } else if (currentFingerCount == 0) {
2828 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002829 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002830 *outFinishPreviousGesture = true;
2831 }
2832
2833 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2834 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2835 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002836 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2837 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002838 lastFingerCount == 1) {
2839 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002840 float x, y;
2841 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002842 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2843 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002844 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002845
2846 mPointerGesture.tapUpTime = when;
2847 getContext()->requestTimeoutAtTime(when +
2848 mConfig.pointerGestureTapDragInterval);
2849
2850 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002851 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002852 mPointerGesture.currentGestureIdBits.clear();
2853 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2854 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2855 mPointerGesture.currentGestureProperties[0].clear();
2856 mPointerGesture.currentGestureProperties[0].id =
2857 mPointerGesture.activeGestureId;
2858 mPointerGesture.currentGestureProperties[0].toolType =
2859 AMOTION_EVENT_TOOL_TYPE_FINGER;
2860 mPointerGesture.currentGestureCoords[0].clear();
2861 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2862 mPointerGesture.tapX);
2863 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2864 mPointerGesture.tapY);
2865 mPointerGesture.currentGestureCoords[0]
2866 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2867
2868 tapped = true;
2869 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002870 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2871 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002872 }
2873 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002874 if (DEBUG_GESTURES) {
2875 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2876 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2877 (when - mPointerGesture.tapDownTime) * 0.000001f);
2878 } else {
2879 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2880 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002881 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002882 }
2883 }
2884
2885 mPointerVelocityControl.reset();
2886
2887 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002888 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002889 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002890 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002891 mPointerGesture.currentGestureIdBits.clear();
2892 }
2893 } else if (currentFingerCount == 1) {
2894 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2895 // The pointer follows the active touch point.
2896 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2897 // When in TAP_DRAG, emit MOVE events at the pointer location.
2898 ALOG_ASSERT(activeTouchId >= 0);
2899
Michael Wright227c5542020-07-02 18:30:52 +01002900 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2901 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002902 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002903 float x, y;
2904 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002905 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2906 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002907 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002908 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002909 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2910 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002911 }
2912 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002913 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2914 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002915 }
Michael Wright227c5542020-07-02 18:30:52 +01002916 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2917 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002918 }
2919
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002920 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002921 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002922 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002923 } else {
2924 mPointerVelocityControl.reset();
2925 }
2926
2927 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002928 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00002929 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002930 down = true;
2931 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002932 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01002933 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002934 *outFinishPreviousGesture = true;
2935 }
2936 mPointerGesture.activeGestureId = 0;
2937 down = false;
2938 }
2939
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002940 float x, y;
2941 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002942
2943 mPointerGesture.currentGestureIdBits.clear();
2944 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2945 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2946 mPointerGesture.currentGestureProperties[0].clear();
2947 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2948 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2949 mPointerGesture.currentGestureCoords[0].clear();
2950 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2951 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2952 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2953 down ? 1.0f : 0.0f);
2954
2955 if (lastFingerCount == 0 && currentFingerCount != 0) {
2956 mPointerGesture.resetTap();
2957 mPointerGesture.tapDownTime = when;
2958 mPointerGesture.tapX = x;
2959 mPointerGesture.tapY = y;
2960 }
2961 } else {
2962 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002963 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002964 }
2965
2966 mPointerController->setButtonState(mCurrentRawState.buttonState);
2967
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002968 if (DEBUG_GESTURES) {
2969 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
2970 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
2971 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
2972 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
2973 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
2974 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
2975 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
2976 uint32_t id = idBits.clearFirstMarkedBit();
2977 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2978 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
2979 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
2980 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
2981 "x=%0.3f, y=%0.3f, pressure=%0.3f",
2982 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
2983 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
2984 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
2985 }
2986 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
2987 uint32_t id = idBits.clearFirstMarkedBit();
2988 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
2989 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
2990 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
2991 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
2992 "x=%0.3f, y=%0.3f, pressure=%0.3f",
2993 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
2994 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
2995 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
2996 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002997 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002998 return true;
2999}
3000
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003001bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3002 if (mPointerGesture.activeTouchId < 0) {
3003 mPointerGesture.resetQuietTime();
3004 return false;
3005 }
3006
3007 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3008 return true;
3009 }
3010
3011 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3012 bool isQuietTime = false;
3013 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3014 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3015 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3016 currentFingerCount < 2) {
3017 // Enter quiet time when exiting swipe or freeform state.
3018 // This is to prevent accidentally entering the hover state and flinging the
3019 // pointer when finishing a swipe and there is still one pointer left onscreen.
3020 isQuietTime = true;
3021 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3022 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3023 // Enter quiet time when releasing the button and there are still two or more
3024 // fingers down. This may indicate that one finger was used to press the button
3025 // but it has not gone up yet.
3026 isQuietTime = true;
3027 }
3028 if (isQuietTime) {
3029 mPointerGesture.quietTime = when;
3030 }
3031 return isQuietTime;
3032}
3033
3034std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3035 int32_t bestId = -1;
3036 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3037 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3038 uint32_t id = idBits.clearFirstMarkedBit();
3039 std::optional<float> vx =
3040 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3041 std::optional<float> vy =
3042 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3043 if (vx && vy) {
3044 float speed = hypotf(*vx, *vy);
3045 if (speed > bestSpeed) {
3046 bestId = id;
3047 bestSpeed = speed;
3048 }
3049 }
3050 }
3051 return std::make_pair(bestId, bestSpeed);
3052}
3053
3054void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3055 bool* finishPreviousGesture) {
3056 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3057 // to move before deciding what to do.
3058 //
3059 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3060 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3061 // just a press or long-press at the pointer location.
3062 //
3063 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3064 // pointer location.
3065 //
3066 // When the two fingers move enough or when additional fingers are added, we make a decision to
3067 // transition into SWIPE or FREEFORM mode accordingly.
3068 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3069 ALOG_ASSERT(activeTouchId >= 0);
3070
3071 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3072 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3073 bool settled =
3074 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3075 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3076 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3077 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3078 *finishPreviousGesture = true;
3079 } else if (!settled && currentFingerCount > lastFingerCount) {
3080 // Additional pointers have gone down but not yet settled.
3081 // Reset the gesture.
3082 ALOGD_IF(DEBUG_GESTURES,
3083 "Gestures: Resetting gesture since additional pointers went down for "
3084 "MULTITOUCH, settle time remaining %0.3fms",
3085 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3086 when) * 0.000001f);
3087 *cancelPreviousGesture = true;
3088 } else {
3089 // Continue previous gesture.
3090 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3091 }
3092
3093 if (*finishPreviousGesture || *cancelPreviousGesture) {
3094 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3095 mPointerGesture.activeGestureId = 0;
3096 mPointerGesture.referenceIdBits.clear();
3097 mPointerVelocityControl.reset();
3098
3099 // Use the centroid and pointer location as the reference points for the gesture.
3100 ALOGD_IF(DEBUG_GESTURES,
3101 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3102 "%0.3fms",
3103 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3104 when) * 0.000001f);
3105 mCurrentRawState.rawPointerData
3106 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3107 &mPointerGesture.referenceTouchY);
3108 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3109 &mPointerGesture.referenceGestureY);
3110 }
3111
3112 // Clear the reference deltas for fingers not yet included in the reference calculation.
3113 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3114 ~mPointerGesture.referenceIdBits.value);
3115 !idBits.isEmpty();) {
3116 uint32_t id = idBits.clearFirstMarkedBit();
3117 mPointerGesture.referenceDeltas[id].dx = 0;
3118 mPointerGesture.referenceDeltas[id].dy = 0;
3119 }
3120 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3121
3122 // Add delta for all fingers and calculate a common movement delta.
3123 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3124 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3125 mCurrentCookedState.fingerIdBits.value);
3126 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3127 bool first = (idBits == commonIdBits);
3128 uint32_t id = idBits.clearFirstMarkedBit();
3129 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3130 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3131 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3132 delta.dx += cpd.x - lpd.x;
3133 delta.dy += cpd.y - lpd.y;
3134
3135 if (first) {
3136 commonDeltaRawX = delta.dx;
3137 commonDeltaRawY = delta.dy;
3138 } else {
3139 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3140 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3141 }
3142 }
3143
3144 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3145 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3146 float dist[MAX_POINTER_ID + 1];
3147 int32_t distOverThreshold = 0;
3148 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3149 uint32_t id = idBits.clearFirstMarkedBit();
3150 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3151 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3152 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3153 distOverThreshold += 1;
3154 }
3155 }
3156
3157 // Only transition when at least two pointers have moved further than
3158 // the minimum distance threshold.
3159 if (distOverThreshold >= 2) {
3160 if (currentFingerCount > 2) {
3161 // There are more than two pointers, switch to FREEFORM.
3162 ALOGD_IF(DEBUG_GESTURES,
3163 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3164 currentFingerCount);
3165 *cancelPreviousGesture = true;
3166 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3167 } else {
3168 // There are exactly two pointers.
3169 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3170 uint32_t id1 = idBits.clearFirstMarkedBit();
3171 uint32_t id2 = idBits.firstMarkedBit();
3172 const RawPointerData::Pointer& p1 =
3173 mCurrentRawState.rawPointerData.pointerForId(id1);
3174 const RawPointerData::Pointer& p2 =
3175 mCurrentRawState.rawPointerData.pointerForId(id2);
3176 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3177 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3178 // There are two pointers but they are too far apart for a SWIPE,
3179 // switch to FREEFORM.
3180 ALOGD_IF(DEBUG_GESTURES,
3181 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3182 mutualDistance, mPointerGestureMaxSwipeWidth);
3183 *cancelPreviousGesture = true;
3184 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3185 } else {
3186 // There are two pointers. Wait for both pointers to start moving
3187 // before deciding whether this is a SWIPE or FREEFORM gesture.
3188 float dist1 = dist[id1];
3189 float dist2 = dist[id2];
3190 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3191 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3192 // Calculate the dot product of the displacement vectors.
3193 // When the vectors are oriented in approximately the same direction,
3194 // the angle betweeen them is near zero and the cosine of the angle
3195 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3196 // mag(v2).
3197 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3198 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3199 float dx1 = delta1.dx * mPointerXZoomScale;
3200 float dy1 = delta1.dy * mPointerYZoomScale;
3201 float dx2 = delta2.dx * mPointerXZoomScale;
3202 float dy2 = delta2.dy * mPointerYZoomScale;
3203 float dot = dx1 * dx2 + dy1 * dy2;
3204 float cosine = dot / (dist1 * dist2); // denominator always > 0
3205 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3206 // Pointers are moving in the same direction. Switch to SWIPE.
3207 ALOGD_IF(DEBUG_GESTURES,
3208 "Gestures: PRESS transitioned to SWIPE, "
3209 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3210 "cosine %0.3f >= %0.3f",
3211 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3212 mConfig.pointerGestureMultitouchMinDistance, cosine,
3213 mConfig.pointerGestureSwipeTransitionAngleCosine);
3214 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3215 } else {
3216 // Pointers are moving in different directions. Switch to FREEFORM.
3217 ALOGD_IF(DEBUG_GESTURES,
3218 "Gestures: PRESS transitioned to FREEFORM, "
3219 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3220 "cosine %0.3f < %0.3f",
3221 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3222 mConfig.pointerGestureMultitouchMinDistance, cosine,
3223 mConfig.pointerGestureSwipeTransitionAngleCosine);
3224 *cancelPreviousGesture = true;
3225 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3226 }
3227 }
3228 }
3229 }
3230 }
3231 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3232 // Switch from SWIPE to FREEFORM if additional pointers go down.
3233 // Cancel previous gesture.
3234 if (currentFingerCount > 2) {
3235 ALOGD_IF(DEBUG_GESTURES,
3236 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3237 currentFingerCount);
3238 *cancelPreviousGesture = true;
3239 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3240 }
3241 }
3242
3243 // Move the reference points based on the overall group motion of the fingers
3244 // except in PRESS mode while waiting for a transition to occur.
3245 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3246 (commonDeltaRawX || commonDeltaRawY)) {
3247 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3248 uint32_t id = idBits.clearFirstMarkedBit();
3249 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3250 delta.dx = 0;
3251 delta.dy = 0;
3252 }
3253
3254 mPointerGesture.referenceTouchX += commonDeltaRawX;
3255 mPointerGesture.referenceTouchY += commonDeltaRawY;
3256
3257 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3258 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3259
3260 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3261 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3262
3263 mPointerGesture.referenceGestureX += commonDeltaX;
3264 mPointerGesture.referenceGestureY += commonDeltaY;
3265 }
3266
3267 // Report gestures.
3268 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3269 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3270 // PRESS or SWIPE mode.
3271 ALOGD_IF(DEBUG_GESTURES,
3272 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3273 "currentTouchPointerCount=%d",
3274 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3275 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3276
3277 mPointerGesture.currentGestureIdBits.clear();
3278 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3279 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3280 mPointerGesture.currentGestureProperties[0].clear();
3281 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3282 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3283 mPointerGesture.currentGestureCoords[0].clear();
3284 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3285 mPointerGesture.referenceGestureX);
3286 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3287 mPointerGesture.referenceGestureY);
3288 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3289 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3290 float xOffset = static_cast<float>(commonDeltaRawX) /
3291 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3292 float yOffset = static_cast<float>(commonDeltaRawY) /
3293 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3294 mPointerGesture.currentGestureCoords[0]
3295 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3296 mPointerGesture.currentGestureCoords[0]
3297 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3298 }
3299 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3300 // FREEFORM mode.
3301 ALOGD_IF(DEBUG_GESTURES,
3302 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3303 "currentTouchPointerCount=%d",
3304 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3305 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3306
3307 mPointerGesture.currentGestureIdBits.clear();
3308
3309 BitSet32 mappedTouchIdBits;
3310 BitSet32 usedGestureIdBits;
3311 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3312 // Initially, assign the active gesture id to the active touch point
3313 // if there is one. No other touch id bits are mapped yet.
3314 if (!*cancelPreviousGesture) {
3315 mappedTouchIdBits.markBit(activeTouchId);
3316 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3317 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3318 mPointerGesture.activeGestureId;
3319 } else {
3320 mPointerGesture.activeGestureId = -1;
3321 }
3322 } else {
3323 // Otherwise, assume we mapped all touches from the previous frame.
3324 // Reuse all mappings that are still applicable.
3325 mappedTouchIdBits.value =
3326 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3327 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3328
3329 // Check whether we need to choose a new active gesture id because the
3330 // current went went up.
3331 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3332 ~mCurrentCookedState.fingerIdBits.value);
3333 !upTouchIdBits.isEmpty();) {
3334 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3335 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3336 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3337 mPointerGesture.activeGestureId = -1;
3338 break;
3339 }
3340 }
3341 }
3342
3343 ALOGD_IF(DEBUG_GESTURES,
3344 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3345 "activeGestureId=%d",
3346 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3347
3348 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3349 for (uint32_t i = 0; i < currentFingerCount; i++) {
3350 uint32_t touchId = idBits.clearFirstMarkedBit();
3351 uint32_t gestureId;
3352 if (!mappedTouchIdBits.hasBit(touchId)) {
3353 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3354 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3355 ALOGD_IF(DEBUG_GESTURES,
3356 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3357 gestureId);
3358 } else {
3359 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3360 ALOGD_IF(DEBUG_GESTURES,
3361 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3362 touchId, gestureId);
3363 }
3364 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3365 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3366
3367 const RawPointerData::Pointer& pointer =
3368 mCurrentRawState.rawPointerData.pointerForId(touchId);
3369 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3370 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3371 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3372
3373 mPointerGesture.currentGestureProperties[i].clear();
3374 mPointerGesture.currentGestureProperties[i].id = gestureId;
3375 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3376 mPointerGesture.currentGestureCoords[i].clear();
3377 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3378 mPointerGesture.referenceGestureX +
3379 deltaX);
3380 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3381 mPointerGesture.referenceGestureY +
3382 deltaY);
3383 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3384 }
3385
3386 if (mPointerGesture.activeGestureId < 0) {
3387 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3388 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3389 mPointerGesture.activeGestureId);
3390 }
3391 }
3392}
3393
Harry Cutts714d1ad2022-08-24 16:36:43 +00003394void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3395 const RawPointerData::Pointer& currentPointer =
3396 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3397 const RawPointerData::Pointer& lastPointer =
3398 mLastRawState.rawPointerData.pointerForId(pointerId);
3399 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3400 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3401
3402 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3403 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3404
3405 mPointerController->move(deltaX, deltaY);
3406}
3407
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003408std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3409 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003410 mPointerSimple.currentCoords.clear();
3411 mPointerSimple.currentProperties.clear();
3412
3413 bool down, hovering;
3414 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3415 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3416 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003417 mPointerController
3418 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3419 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003420
3421 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3422 down = !hovering;
3423
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003424 float x, y;
3425 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003426 mPointerSimple.currentCoords.copyFrom(
3427 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3428 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3429 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3430 mPointerSimple.currentProperties.id = 0;
3431 mPointerSimple.currentProperties.toolType =
3432 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3433 } else {
3434 down = false;
3435 hovering = false;
3436 }
3437
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003438 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003439}
3440
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003441std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3442 uint32_t policyFlags) {
3443 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003444}
3445
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003446std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3447 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003448 mPointerSimple.currentCoords.clear();
3449 mPointerSimple.currentProperties.clear();
3450
3451 bool down, hovering;
3452 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3453 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003454 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003455 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003456 } else {
3457 mPointerVelocityControl.reset();
3458 }
3459
3460 down = isPointerDown(mCurrentRawState.buttonState);
3461 hovering = !down;
3462
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003463 float x, y;
3464 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003465 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003466 mPointerSimple.currentCoords.copyFrom(
3467 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3468 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3469 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3470 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3471 hovering ? 0.0f : 1.0f);
3472 mPointerSimple.currentProperties.id = 0;
3473 mPointerSimple.currentProperties.toolType =
3474 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3475 } else {
3476 mPointerVelocityControl.reset();
3477
3478 down = false;
3479 hovering = false;
3480 }
3481
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003482 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003483}
3484
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003485std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3486 uint32_t policyFlags) {
3487 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003488
3489 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003490
3491 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003492}
3493
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003494std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3495 uint32_t policyFlags, bool down,
3496 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003497 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3498 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003499 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003500 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003501
3502 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003503 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003504 mPointerController->clearSpots();
3505 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003506 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003507 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003508 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003509 }
Garfield Tan9514d782020-11-10 16:37:23 -08003510 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003511
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003512 float xCursorPosition, yCursorPosition;
3513 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003514
3515 if (mPointerSimple.down && !down) {
3516 mPointerSimple.down = false;
3517
3518 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003519 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3520 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3521 0, metaState, mLastRawState.buttonState,
3522 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3523 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3524 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3525 yCursorPosition, mPointerSimple.downTime,
3526 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003527 }
3528
3529 if (mPointerSimple.hovering && !hovering) {
3530 mPointerSimple.hovering = false;
3531
3532 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003533 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3534 mSource, displayId, policyFlags,
3535 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3536 mLastRawState.buttonState, MotionClassification::NONE,
3537 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3538 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3539 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3540 yCursorPosition, mPointerSimple.downTime,
3541 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003542 }
3543
3544 if (down) {
3545 if (!mPointerSimple.down) {
3546 mPointerSimple.down = true;
3547 mPointerSimple.downTime = when;
3548
3549 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003550 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3551 mSource, displayId, policyFlags,
3552 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3553 mCurrentRawState.buttonState, MotionClassification::NONE,
3554 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3555 &mPointerSimple.currentProperties,
3556 &mPointerSimple.currentCoords, mOrientedXPrecision,
3557 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3558 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003559 }
3560
3561 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003562 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3563 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3564 0, 0, metaState, mCurrentRawState.buttonState,
3565 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3566 &mPointerSimple.currentProperties,
3567 &mPointerSimple.currentCoords, mOrientedXPrecision,
3568 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3569 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003570 }
3571
3572 if (hovering) {
3573 if (!mPointerSimple.hovering) {
3574 mPointerSimple.hovering = true;
3575
3576 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003577 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3578 mSource, displayId, policyFlags,
3579 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3580 mCurrentRawState.buttonState, MotionClassification::NONE,
3581 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3582 &mPointerSimple.currentProperties,
3583 &mPointerSimple.currentCoords, mOrientedXPrecision,
3584 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3585 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003586 }
3587
3588 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003589 out.push_back(
3590 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3591 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3592 metaState, mCurrentRawState.buttonState,
3593 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3594 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3595 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3596 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003597 }
3598
3599 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3600 float vscroll = mCurrentRawState.rawVScroll;
3601 float hscroll = mCurrentRawState.rawHScroll;
3602 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3603 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3604
3605 // Send scroll.
3606 PointerCoords pointerCoords;
3607 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3608 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3609 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3610
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003611 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3612 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3613 0, 0, metaState, mCurrentRawState.buttonState,
3614 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3615 &mPointerSimple.currentProperties, &pointerCoords,
3616 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3617 yCursorPosition, mPointerSimple.downTime,
3618 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003619 }
3620
3621 // Save state.
3622 if (down || hovering) {
3623 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3624 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003625 mPointerSimple.displayId = displayId;
3626 mPointerSimple.source = mSource;
3627 mPointerSimple.lastCursorX = xCursorPosition;
3628 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003629 } else {
3630 mPointerSimple.reset();
3631 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003632 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003633}
3634
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003635std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3636 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003637 std::list<NotifyArgs> out;
3638 if (mPointerSimple.down || mPointerSimple.hovering) {
3639 int32_t metaState = getContext()->getGlobalMetaState();
3640 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3641 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3642 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3643 metaState, mLastRawState.buttonState,
3644 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3645 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3646 mOrientedXPrecision, mOrientedYPrecision,
3647 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3648 mPointerSimple.downTime,
3649 /* videoFrames */ {}));
3650 if (mPointerController != nullptr) {
3651 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3652 }
3653 }
3654 mPointerSimple.reset();
3655 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003656}
3657
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003658NotifyMotionArgs TouchInputMapper::dispatchMotion(
3659 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3660 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003661 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3662 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003663 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003664 PointerCoords pointerCoords[MAX_POINTERS];
3665 PointerProperties pointerProperties[MAX_POINTERS];
3666 uint32_t pointerCount = 0;
3667 while (!idBits.isEmpty()) {
3668 uint32_t id = idBits.clearFirstMarkedBit();
3669 uint32_t index = idToIndex[id];
3670 pointerProperties[pointerCount].copyFrom(properties[index]);
3671 pointerCoords[pointerCount].copyFrom(coords[index]);
3672
3673 if (changedId >= 0 && id == uint32_t(changedId)) {
3674 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3675 }
3676
3677 pointerCount += 1;
3678 }
3679
3680 ALOG_ASSERT(pointerCount != 0);
3681
3682 if (changedId >= 0 && pointerCount == 1) {
3683 // Replace initial down and final up action.
3684 // We can compare the action without masking off the changed pointer index
3685 // because we know the index is 0.
3686 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3687 action = AMOTION_EVENT_ACTION_DOWN;
3688 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003689 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3690 action = AMOTION_EVENT_ACTION_CANCEL;
3691 } else {
3692 action = AMOTION_EVENT_ACTION_UP;
3693 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003694 } else {
3695 // Can't happen.
3696 ALOG_ASSERT(false);
3697 }
3698 }
3699 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3700 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003701 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003702 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003703 }
3704 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3705 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003706 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003707 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003708 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003709 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3710 policyFlags, action, actionButton, flags, metaState, buttonState,
3711 classification, edgeFlags, pointerCount, pointerProperties,
3712 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3713 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003714}
3715
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003716std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3717 std::list<NotifyArgs> out;
3718 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3719 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3720 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003721}
3722
Prabir Pradhan1728b212021-10-19 16:00:03 -07003723bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003724 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003725 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003726 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003727}
3728
3729const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3730 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003731 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3732 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3733 "left=%d, top=%d, right=%d, bottom=%d",
3734 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3735 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003736
3737 if (virtualKey.isHit(x, y)) {
3738 return &virtualKey;
3739 }
3740 }
3741
3742 return nullptr;
3743}
3744
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003745void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3746 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3747 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003748
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003749 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003750
3751 if (currentPointerCount == 0) {
3752 // No pointers to assign.
3753 return;
3754 }
3755
3756 if (lastPointerCount == 0) {
3757 // All pointers are new.
3758 for (uint32_t i = 0; i < currentPointerCount; i++) {
3759 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003760 current.rawPointerData.pointers[i].id = id;
3761 current.rawPointerData.idToIndex[id] = i;
3762 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003763 }
3764 return;
3765 }
3766
3767 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003768 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003769 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003770 uint32_t id = last.rawPointerData.pointers[0].id;
3771 current.rawPointerData.pointers[0].id = id;
3772 current.rawPointerData.idToIndex[id] = 0;
3773 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003774 return;
3775 }
3776
3777 // General case.
3778 // We build a heap of squared euclidean distances between current and last pointers
3779 // associated with the current and last pointer indices. Then, we find the best
3780 // match (by distance) for each current pointer.
3781 // The pointers must have the same tool type but it is possible for them to
3782 // transition from hovering to touching or vice-versa while retaining the same id.
3783 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3784
3785 uint32_t heapSize = 0;
3786 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3787 currentPointerIndex++) {
3788 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3789 lastPointerIndex++) {
3790 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003791 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003792 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003793 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003794 if (currentPointer.toolType == lastPointer.toolType) {
3795 int64_t deltaX = currentPointer.x - lastPointer.x;
3796 int64_t deltaY = currentPointer.y - lastPointer.y;
3797
3798 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3799
3800 // Insert new element into the heap (sift up).
3801 heap[heapSize].currentPointerIndex = currentPointerIndex;
3802 heap[heapSize].lastPointerIndex = lastPointerIndex;
3803 heap[heapSize].distance = distance;
3804 heapSize += 1;
3805 }
3806 }
3807 }
3808
3809 // Heapify
3810 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3811 startIndex -= 1;
3812 for (uint32_t parentIndex = startIndex;;) {
3813 uint32_t childIndex = parentIndex * 2 + 1;
3814 if (childIndex >= heapSize) {
3815 break;
3816 }
3817
3818 if (childIndex + 1 < heapSize &&
3819 heap[childIndex + 1].distance < heap[childIndex].distance) {
3820 childIndex += 1;
3821 }
3822
3823 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3824 break;
3825 }
3826
3827 swap(heap[parentIndex], heap[childIndex]);
3828 parentIndex = childIndex;
3829 }
3830 }
3831
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003832 if (DEBUG_POINTER_ASSIGNMENT) {
3833 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3834 for (size_t i = 0; i < heapSize; i++) {
3835 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3836 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3837 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003838 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003839
3840 // Pull matches out by increasing order of distance.
3841 // To avoid reassigning pointers that have already been matched, the loop keeps track
3842 // of which last and current pointers have been matched using the matchedXXXBits variables.
3843 // It also tracks the used pointer id bits.
3844 BitSet32 matchedLastBits(0);
3845 BitSet32 matchedCurrentBits(0);
3846 BitSet32 usedIdBits(0);
3847 bool first = true;
3848 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3849 while (heapSize > 0) {
3850 if (first) {
3851 // The first time through the loop, we just consume the root element of
3852 // the heap (the one with smallest distance).
3853 first = false;
3854 } else {
3855 // Previous iterations consumed the root element of the heap.
3856 // Pop root element off of the heap (sift down).
3857 heap[0] = heap[heapSize];
3858 for (uint32_t parentIndex = 0;;) {
3859 uint32_t childIndex = parentIndex * 2 + 1;
3860 if (childIndex >= heapSize) {
3861 break;
3862 }
3863
3864 if (childIndex + 1 < heapSize &&
3865 heap[childIndex + 1].distance < heap[childIndex].distance) {
3866 childIndex += 1;
3867 }
3868
3869 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3870 break;
3871 }
3872
3873 swap(heap[parentIndex], heap[childIndex]);
3874 parentIndex = childIndex;
3875 }
3876
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003877 if (DEBUG_POINTER_ASSIGNMENT) {
3878 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3879 for (size_t j = 0; j < heapSize; j++) {
3880 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3881 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3882 heap[j].distance);
3883 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003884 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003885 }
3886
3887 heapSize -= 1;
3888
3889 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3890 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3891
3892 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3893 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3894
3895 matchedCurrentBits.markBit(currentPointerIndex);
3896 matchedLastBits.markBit(lastPointerIndex);
3897
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003898 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3899 current.rawPointerData.pointers[currentPointerIndex].id = id;
3900 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3901 current.rawPointerData.markIdBit(id,
3902 current.rawPointerData.isHovering(
3903 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003904 usedIdBits.markBit(id);
3905
Harry Cutts45483602022-08-24 14:36:48 +00003906 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3907 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3908 ", distance=%" PRIu64,
3909 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003910 break;
3911 }
3912 }
3913
3914 // Assign fresh ids to pointers that were not matched in the process.
3915 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3916 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3917 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3918
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003919 current.rawPointerData.pointers[currentPointerIndex].id = id;
3920 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3921 current.rawPointerData.markIdBit(id,
3922 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003923
Harry Cutts45483602022-08-24 14:36:48 +00003924 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3925 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
3926 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003927 }
3928}
3929
3930int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3931 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3932 return AKEY_STATE_VIRTUAL;
3933 }
3934
3935 for (const VirtualKey& virtualKey : mVirtualKeys) {
3936 if (virtualKey.keyCode == keyCode) {
3937 return AKEY_STATE_UP;
3938 }
3939 }
3940
3941 return AKEY_STATE_UNKNOWN;
3942}
3943
3944int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3945 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3946 return AKEY_STATE_VIRTUAL;
3947 }
3948
3949 for (const VirtualKey& virtualKey : mVirtualKeys) {
3950 if (virtualKey.scanCode == scanCode) {
3951 return AKEY_STATE_UP;
3952 }
3953 }
3954
3955 return AKEY_STATE_UNKNOWN;
3956}
3957
Siarhei Vishniakou74007942022-06-13 13:57:47 -07003958bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
3959 const std::vector<int32_t>& keyCodes,
3960 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003961 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07003962 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003963 if (virtualKey.keyCode == keyCodes[i]) {
3964 outFlags[i] = 1;
3965 }
3966 }
3967 }
3968
3969 return true;
3970}
3971
3972std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3973 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003974 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003975 return std::make_optional(mPointerController->getDisplayId());
3976 } else {
3977 return std::make_optional(mViewport.displayId);
3978 }
3979 }
3980 return std::nullopt;
3981}
3982
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003983} // namespace android