blob: cefc44ef7aff8009690a22de312224008d13c427 [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
54static bool isPointInRect(const Rect& rect, int32_t x, int32_t y) {
55 // Consider all four sides as "inclusive".
56 return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
57}
58
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070059template <typename T>
60inline static void swap(T& a, T& b) {
61 T temp = a;
62 a = b;
63 b = temp;
64}
65
66static float calculateCommonVector(float a, float b) {
67 if (a > 0 && b > 0) {
68 return a < b ? a : b;
69 } else if (a < 0 && b < 0) {
70 return a > b ? a : b;
71 } else {
72 return 0;
73 }
74}
75
76inline static float distance(float x1, float y1, float x2, float y2) {
77 return hypotf(x1 - x2, y1 - y2);
78}
79
80inline static int32_t signExtendNybble(int32_t value) {
81 return value >= 8 ? value - 16 : value;
82}
83
Prabir Pradhan2d613f42022-11-10 20:22:06 +000084static std::tuple<ui::Size /*displayBounds*/, Rect /*physicalFrame*/> getNaturalDisplayInfo(
Michael Wrighta9cf4192022-12-01 23:46:39 +000085 const DisplayViewport& viewport, ui::Rotation naturalOrientation) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000086 ui::Size rotatedDisplaySize{viewport.deviceWidth, viewport.deviceHeight};
Michael Wrighta9cf4192022-12-01 23:46:39 +000087 if (naturalOrientation == ui::ROTATION_90 || naturalOrientation == ui::ROTATION_270) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000088 std::swap(rotatedDisplaySize.width, rotatedDisplaySize.height);
89 }
90
Michael Wrighta9cf4192022-12-01 23:46:39 +000091 ui::Transform rotate(ui::Transform::toRotationFlags(naturalOrientation),
92 rotatedDisplaySize.width, rotatedDisplaySize.height);
Prabir Pradhan2d613f42022-11-10 20:22:06 +000093
94 Rect physicalFrame{viewport.physicalLeft, viewport.physicalTop, viewport.physicalRight,
95 viewport.physicalBottom};
96 physicalFrame = rotate.transform(physicalFrame);
97
98 LOG_ALWAYS_FATAL_IF(!physicalFrame.isValid());
99 if (physicalFrame.isEmpty()) {
100 ALOGE("Viewport is not set properly: %s", viewport.toString().c_str());
101 physicalFrame.right =
102 physicalFrame.left + (physicalFrame.width() == 0 ? 1 : physicalFrame.width());
103 physicalFrame.bottom =
104 physicalFrame.top + (physicalFrame.height() == 0 ? 1 : physicalFrame.height());
105 }
106 return {rotatedDisplaySize, physicalFrame};
107}
108
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700109// --- RawPointerData ---
110
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700111void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
112 float x = 0, y = 0;
113 uint32_t count = touchingIdBits.count();
114 if (count) {
115 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
116 uint32_t id = idBits.clearFirstMarkedBit();
117 const Pointer& pointer = pointerForId(id);
118 x += pointer.x;
119 y += pointer.y;
120 }
121 x /= count;
122 y /= count;
123 }
124 *outX = x;
125 *outY = y;
126}
127
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700128// --- TouchInputMapper ---
129
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800130TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
131 : InputMapper(deviceContext),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000132 mTouchButtonAccumulator(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700133 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100134 mDeviceMode(DeviceMode::DISABLED),
Michael Wrighta9cf4192022-12-01 23:46:39 +0000135 mInputDeviceOrientation(ui::ROTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700136
137TouchInputMapper::~TouchInputMapper() {}
138
Philip Junker4af3b3d2021-12-14 10:36:55 +0100139uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700140 return mSource;
141}
142
143void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
144 InputMapper::populateDeviceInfo(info);
145
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000146 if (mDeviceMode == DeviceMode::DISABLED) {
147 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700148 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000149
150 info->addMotionRange(mOrientedRanges.x);
151 info->addMotionRange(mOrientedRanges.y);
152 info->addMotionRange(mOrientedRanges.pressure);
153
154 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
155 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
156 //
157 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
158 // motion, i.e. the hardware dimensions, as the finger could move completely across the
159 // touchpad in one sample cycle.
160 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
161 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
162 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
163 x.resolution);
164 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
165 y.resolution);
166 }
167
168 if (mOrientedRanges.size) {
169 info->addMotionRange(*mOrientedRanges.size);
170 }
171
172 if (mOrientedRanges.touchMajor) {
173 info->addMotionRange(*mOrientedRanges.touchMajor);
174 info->addMotionRange(*mOrientedRanges.touchMinor);
175 }
176
177 if (mOrientedRanges.toolMajor) {
178 info->addMotionRange(*mOrientedRanges.toolMajor);
179 info->addMotionRange(*mOrientedRanges.toolMinor);
180 }
181
182 if (mOrientedRanges.orientation) {
183 info->addMotionRange(*mOrientedRanges.orientation);
184 }
185
186 if (mOrientedRanges.distance) {
187 info->addMotionRange(*mOrientedRanges.distance);
188 }
189
190 if (mOrientedRanges.tilt) {
191 info->addMotionRange(*mOrientedRanges.tilt);
192 }
193
194 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
195 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
196 }
197 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
198 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
199 }
200 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
201 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
202 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
203 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat, x.fuzz,
204 x.resolution);
205 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat, y.fuzz,
206 y.resolution);
207 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat, x.fuzz,
208 x.resolution);
209 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat, y.fuzz,
210 y.resolution);
211 }
212 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000213 info->setSupportsUsi(mParameters.supportsUsi);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700214}
215
216void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700217 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800218 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700219 dumpParameters(dump);
220 dumpVirtualKeys(dump);
221 dumpRawPointerAxes(dump);
222 dumpCalibration(dump);
223 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700224 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700225
226 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700227 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
228 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
229 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
230 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
231 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
232 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
233 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
234 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
235 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
236 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
237 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
238 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
239 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
240 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
241
242 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
243 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
244 mLastRawState.rawPointerData.pointerCount);
245 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
246 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
247 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
248 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
249 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
250 "toolType=%d, isHovering=%s\n",
251 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
252 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
253 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
254 pointer.distance, pointer.toolType, toString(pointer.isHovering));
255 }
256
257 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
258 mLastCookedState.buttonState);
259 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
260 mLastCookedState.cookedPointerData.pointerCount);
261 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
262 const PointerProperties& pointerProperties =
263 mLastCookedState.cookedPointerData.pointerProperties[i];
264 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000265 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
266 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
267 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700268 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
269 "toolType=%d, isHovering=%s\n",
270 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000271 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
272 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700273 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
274 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
275 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
276 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
277 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
278 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
279 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
280 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
281 pointerProperties.toolType,
282 toString(mLastCookedState.cookedPointerData.isHovering(i)));
283 }
284
285 dump += INDENT3 "Stylus Fusion:\n";
286 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
287 toString(mExternalStylusConnected));
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000288 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
289 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700290 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
291 mExternalStylusFusionTimeout);
Prabir Pradhan124ea442022-10-28 20:27:44 +0000292 dump += StringPrintf(INDENT4 " External Stylus Buttons Applied: 0x%08x",
293 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700294 dump += INDENT3 "External Stylus State:\n";
295 dumpStylusState(dump, mExternalStylusState);
296
Michael Wright227c5542020-07-02 18:30:52 +0100297 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700298 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
299 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
300 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
301 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
302 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
303 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
304 }
305}
306
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700307std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
308 const InputReaderConfiguration* config,
309 uint32_t changes) {
310 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700311
312 mConfig = *config;
313
314 if (!changes) { // first time only
315 // Configure basic parameters.
316 configureParameters();
317
318 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800319 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000320 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700321
322 // Configure absolute axis information.
323 configureRawPointerAxes();
324
325 // Prepare input device calibration.
326 parseCalibration();
327 resolveCalibration();
328 }
329
330 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
331 // Update location calibration to reflect current settings
332 updateAffineTransformation();
333 }
334
335 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
336 // Update pointer speed.
337 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
338 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
339 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
340 }
341
342 bool resetNeeded = false;
343 if (!changes ||
344 (changes &
345 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800346 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700347 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
348 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
349 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700350 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700351 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700352 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700353 }
354
355 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700356 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000357
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700358 // Send reset, unless this is the first time the device has been configured,
359 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000360 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700361 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700362 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700363}
364
365void TouchInputMapper::resolveExternalStylusPresence() {
366 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800367 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700368 mExternalStylusConnected = !devices.empty();
369
370 if (!mExternalStylusConnected) {
371 resetExternalStylus();
372 }
373}
374
375void TouchInputMapper::configureParameters() {
376 // Use the pointer presentation mode for devices that do not support distinct
377 // multitouch. The spot-based presentation relies on being able to accurately
378 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800379 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100380 ? Parameters::GestureMode::SINGLE_TOUCH
381 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700382
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700383 std::string gestureModeString;
384 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800385 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700386 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100387 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700388 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100389 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700390 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700391 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700392 }
393 }
394
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800395 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700396 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100397 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800398 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700399 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100400 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700401 } else {
402 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100403 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700404 }
405
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800406 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700407
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700408 std::string deviceTypeString;
409 if (getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800410 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700411 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100412 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700413 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100414 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700415 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100416 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700417 } else if (deviceTypeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700418 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700419 }
420 }
421
Michael Wright227c5542020-07-02 18:30:52 +0100422 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700423 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800424 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700425
Michael Wrighta9cf4192022-12-01 23:46:39 +0000426 mParameters.orientation = ui::ROTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700427 std::string orientationString;
428 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700429 orientationString)) {
430 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
431 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
432 } else if (orientationString == "ORIENTATION_90") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000433 mParameters.orientation = ui::ROTATION_90;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700434 } else if (orientationString == "ORIENTATION_180") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000435 mParameters.orientation = ui::ROTATION_180;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700436 } else if (orientationString == "ORIENTATION_270") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000437 mParameters.orientation = ui::ROTATION_270;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700438 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700439 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700440 }
441 }
442
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700443 mParameters.hasAssociatedDisplay = false;
444 mParameters.associatedDisplayIsExternal = false;
445 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100446 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
447 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700448 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100449 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800450 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700451 std::string uniqueDisplayId;
452 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800453 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700454 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
455 }
456 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800457 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700458 mParameters.hasAssociatedDisplay = true;
459 }
460
461 // Initial downs on external touch devices should wake the device.
462 // Normally we don't do this for internal touch screens to prevent them from waking
463 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800464 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700465 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000466
467 mParameters.supportsUsi = false;
468 getDeviceContext().getConfiguration().tryGetProperty("touch.supportsUsi",
469 mParameters.supportsUsi);
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700470
471 mParameters.enableForInactiveViewport = false;
472 getDeviceContext().getConfiguration().tryGetProperty("touch.enableForInactiveViewport",
473 mParameters.enableForInactiveViewport);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700474}
475
476void TouchInputMapper::dumpParameters(std::string& dump) {
477 dump += INDENT3 "Parameters:\n";
478
Dominik Laskowski75788452021-02-09 18:51:25 -0800479 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700480
Dominik Laskowski75788452021-02-09 18:51:25 -0800481 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700482
483 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
484 "displayId='%s'\n",
485 toString(mParameters.hasAssociatedDisplay),
486 toString(mParameters.associatedDisplayIsExternal),
487 mParameters.uniqueDisplayId.c_str());
488 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800489 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhan167c2702022-09-14 00:37:24 +0000490 dump += StringPrintf(INDENT4 "SupportsUsi: %s\n", toString(mParameters.supportsUsi));
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700491 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
492 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700493}
494
495void TouchInputMapper::configureRawPointerAxes() {
496 mRawPointerAxes.clear();
497}
498
499void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
500 dump += INDENT3 "Raw Touch Axes:\n";
501 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
502 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
503 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
504 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
505 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
506 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
507 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
508 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
509 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
510 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
511 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
512 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
513 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
514}
515
516bool TouchInputMapper::hasExternalStylus() const {
517 return mExternalStylusConnected;
518}
519
520/**
521 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000522 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800523 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000524 * 3. Get the matching viewport by either unique id in idc file or by the display type
525 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800526 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700527 */
528std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800529 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000530 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800531 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700532 }
533
Christine Franks2a2293c2022-01-18 11:51:16 -0800534 const std::optional<std::string> associatedDisplayUniqueId =
535 getDeviceContext().getAssociatedDisplayUniqueId();
536 if (associatedDisplayUniqueId) {
537 return getDeviceContext().getAssociatedViewport();
538 }
539
Michael Wright227c5542020-07-02 18:30:52 +0100540 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800541 std::optional<DisplayViewport> viewport =
542 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
543 if (viewport) {
544 return viewport;
545 } else {
546 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
547 mConfig.defaultPointerDisplayId);
548 }
549 }
550
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700551 // Check if uniqueDisplayId is specified in idc file.
552 if (!mParameters.uniqueDisplayId.empty()) {
553 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
554 }
555
556 ViewportType viewportTypeToUse;
557 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100558 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700559 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100560 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700561 }
562
563 std::optional<DisplayViewport> viewport =
564 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100565 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700566 ALOGW("Input device %s should be associated with external display, "
567 "fallback to internal one for the external viewport is not found.",
568 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100569 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700570 }
571
572 return viewport;
573 }
574
575 // No associated display, return a non-display viewport.
576 DisplayViewport newViewport;
577 // Raw width and height in the natural orientation.
578 int32_t rawWidth = mRawPointerAxes.getRawWidth();
579 int32_t rawHeight = mRawPointerAxes.getRawHeight();
580 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
581 return std::make_optional(newViewport);
582}
583
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800584int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
585 if (resolution < 0) {
586 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
587 getDeviceName().c_str());
588 return 0;
589 }
590 return resolution;
591}
592
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800593void TouchInputMapper::initializeSizeRanges() {
594 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
595 mSizeScale = 0.0f;
596 return;
597 }
598
599 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000600 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800601
602 // Size factors.
603 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
604 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
605 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
606 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
607 } else {
608 mSizeScale = 0.0f;
609 }
610
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700611 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
612 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
613 .source = mSource,
614 .min = 0,
615 .max = diagonalSize,
616 .flat = 0,
617 .fuzz = 0,
618 .resolution = 0,
619 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800620
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800621 if (mRawPointerAxes.touchMajor.valid) {
622 mRawPointerAxes.touchMajor.resolution =
623 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700624 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800625 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800626
627 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700628 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800629 if (mRawPointerAxes.touchMinor.valid) {
630 mRawPointerAxes.touchMinor.resolution =
631 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700632 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800633 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800634
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700635 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
636 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
637 .source = mSource,
638 .min = 0,
639 .max = diagonalSize,
640 .flat = 0,
641 .fuzz = 0,
642 .resolution = 0,
643 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800644 if (mRawPointerAxes.toolMajor.valid) {
645 mRawPointerAxes.toolMajor.resolution =
646 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700647 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800648 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800649
650 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700651 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800652 if (mRawPointerAxes.toolMinor.valid) {
653 mRawPointerAxes.toolMinor.resolution =
654 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700655 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800656 }
657
658 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700659 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
660 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
661 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
662 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800663 } else {
664 // Support for other calibrations can be added here.
665 ALOGW("%s calibration is not supported for size ranges at the moment. "
666 "Using raw resolution instead",
667 ftl::enum_string(mCalibration.sizeCalibration).c_str());
668 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800669
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700670 mOrientedRanges.size = InputDeviceInfo::MotionRange{
671 .axis = AMOTION_EVENT_AXIS_SIZE,
672 .source = mSource,
673 .min = 0,
674 .max = 1.0,
675 .flat = 0,
676 .fuzz = 0,
677 .resolution = 0,
678 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800679}
680
681void TouchInputMapper::initializeOrientedRanges() {
682 // Configure X and Y factors.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000683 mXScale = float(mDisplayBounds.width) / mRawPointerAxes.getRawWidth();
684 mYScale = float(mDisplayBounds.height) / mRawPointerAxes.getRawHeight();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800685 mXPrecision = 1.0f / mXScale;
686 mYPrecision = 1.0f / mYScale;
687
688 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
689 mOrientedRanges.x.source = mSource;
690 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
691 mOrientedRanges.y.source = mSource;
692
693 // Scale factor for terms that are not oriented in a particular axis.
694 // If the pixels are square then xScale == yScale otherwise we fake it
695 // by choosing an average.
696 mGeometricScale = avg(mXScale, mYScale);
697
698 initializeSizeRanges();
699
700 // Pressure factors.
701 mPressureScale = 0;
702 float pressureMax = 1.0;
703 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
704 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700705 if (mCalibration.pressureScale) {
706 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800707 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
708 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
709 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
710 }
711 }
712
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700713 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
714 .axis = AMOTION_EVENT_AXIS_PRESSURE,
715 .source = mSource,
716 .min = 0,
717 .max = pressureMax,
718 .flat = 0,
719 .fuzz = 0,
720 .resolution = 0,
721 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800722
723 // Tilt
724 mTiltXCenter = 0;
725 mTiltXScale = 0;
726 mTiltYCenter = 0;
727 mTiltYScale = 0;
728 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
729 if (mHaveTilt) {
730 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
731 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
732 mTiltXScale = M_PI / 180;
733 mTiltYScale = M_PI / 180;
734
735 if (mRawPointerAxes.tiltX.resolution) {
736 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
737 }
738 if (mRawPointerAxes.tiltY.resolution) {
739 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
740 }
741
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700742 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
743 .axis = AMOTION_EVENT_AXIS_TILT,
744 .source = mSource,
745 .min = 0,
746 .max = M_PI_2,
747 .flat = 0,
748 .fuzz = 0,
749 .resolution = 0,
750 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800751 }
752
753 // Orientation
754 mOrientationScale = 0;
755 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700756 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
757 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
758 .source = mSource,
759 .min = -M_PI,
760 .max = M_PI,
761 .flat = 0,
762 .fuzz = 0,
763 .resolution = 0,
764 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800765
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800766 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
767 if (mCalibration.orientationCalibration ==
768 Calibration::OrientationCalibration::INTERPOLATED) {
769 if (mRawPointerAxes.orientation.valid) {
770 if (mRawPointerAxes.orientation.maxValue > 0) {
771 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
772 } else if (mRawPointerAxes.orientation.minValue < 0) {
773 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
774 } else {
775 mOrientationScale = 0;
776 }
777 }
778 }
779
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700780 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
781 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
782 .source = mSource,
783 .min = -M_PI_2,
784 .max = M_PI_2,
785 .flat = 0,
786 .fuzz = 0,
787 .resolution = 0,
788 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800789 }
790
791 // Distance
792 mDistanceScale = 0;
793 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
794 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700795 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800796 }
797
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700798 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800799
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700800 .axis = AMOTION_EVENT_AXIS_DISTANCE,
801 .source = mSource,
802 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
803 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
804 .flat = 0,
805 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
806 .resolution = 0,
807 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800808 }
809
810 // Compute oriented precision, scales and ranges.
811 // Note that the maximum value reported is an inclusive maximum value so it is one
812 // unit less than the total width or height of the display.
813 switch (mInputDeviceOrientation) {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000814 case ui::ROTATION_90:
815 case ui::ROTATION_270:
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800816 mOrientedXPrecision = mYPrecision;
817 mOrientedYPrecision = mXPrecision;
818
819 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000820 mOrientedRanges.x.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800821 mOrientedRanges.x.flat = 0;
822 mOrientedRanges.x.fuzz = 0;
823 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
824
825 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000826 mOrientedRanges.y.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800827 mOrientedRanges.y.flat = 0;
828 mOrientedRanges.y.fuzz = 0;
829 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
830 break;
831
832 default:
833 mOrientedXPrecision = mXPrecision;
834 mOrientedYPrecision = mYPrecision;
835
836 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000837 mOrientedRanges.x.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800838 mOrientedRanges.x.flat = 0;
839 mOrientedRanges.x.fuzz = 0;
840 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
841
842 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000843 mOrientedRanges.y.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800844 mOrientedRanges.y.flat = 0;
845 mOrientedRanges.y.fuzz = 0;
846 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
847 break;
848 }
849}
850
Prabir Pradhan1728b212021-10-19 16:00:03 -0700851void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000852 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700853
854 resolveExternalStylusPresence();
855
856 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100857 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000858 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700859 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100860 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700861 if (hasStylus()) {
862 mSource |= AINPUT_SOURCE_STYLUS;
Harry Cutts16a24cc2022-10-26 15:22:19 +0000863 } else {
864 mSource |= AINPUT_SOURCE_TOUCHPAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700865 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800866 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700867 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100868 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700869 if (hasStylus()) {
870 mSource |= AINPUT_SOURCE_STYLUS;
871 }
872 if (hasExternalStylus()) {
873 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
874 }
Michael Wright227c5542020-07-02 18:30:52 +0100875 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700876 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100877 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700878 } else {
879 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100880 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700881 }
882
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000883 const std::optional<DisplayViewport> newViewportOpt = findViewport();
884
885 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700886 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
887 ALOGW("Touch device '%s' did not report support for X or Y axis! "
888 "The device will be inoperable.",
889 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100890 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000891 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700892 ALOGI("Touch device '%s' could not query the properties of its associated "
893 "display. The device will be inoperable until the display size "
894 "becomes available.",
895 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100896 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700897 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000898 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
899 getDeviceName().c_str(), getDeviceId());
900 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000901 }
902
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700903 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000904 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000905 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
906 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
907 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
908 const float rawMeanResolution =
909 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700910
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000911 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
912 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700913 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700914 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000915 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
916 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
917 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700918
Michael Wright227c5542020-07-02 18:30:52 +0100919 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000920 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700921
Prabir Pradhan1728b212021-10-19 16:00:03 -0700922 // Apply the inverse of the input device orientation so that the input device is
923 // configured in the same orientation as the viewport. The input device orientation will
924 // be re-applied by mInputDeviceOrientation.
Michael Wrighta9cf4192022-12-01 23:46:39 +0000925 const ui::Rotation naturalDeviceOrientation =
926 mViewport.orientation - mParameters.orientation;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700927
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000928 std::tie(mDisplayBounds, mPhysicalFrameInDisplay) =
929 getNaturalDisplayInfo(mViewport, naturalDeviceOrientation);
Prabir Pradhan5632d622021-09-06 07:57:20 -0700930
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000931 // InputReader works in the un-rotated display coordinate space, so we don't need to do
932 // anything if the device is already orientation-aware. If the device is not
933 // orientation-aware, then we need to apply the inverse rotation of the display so that
934 // when the display rotation is applied later as a part of the per-window transform, we
935 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700936 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +0000937 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000938 : getInverseRotation(mViewport.orientation);
939 // For orientation-aware devices that work in the un-rotated coordinate space, the
940 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000941 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000942 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700943
944 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +0000945 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700946 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000947 mDisplayBounds = rawSize;
948 mPhysicalFrameInDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +0000949 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700950 }
951 }
952
953 // If moving between pointer modes, need to reset some state.
954 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
955 if (deviceModeChanged) {
956 mOrientedRanges.clear();
957 }
958
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800959 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
960 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100961 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800962 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000963 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
964 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800965 if (mPointerController == nullptr) {
966 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700967 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000968 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800969 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
970 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700971 } else {
lilinnandef700b2022-06-17 19:32:01 +0800972 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
973 !mConfig.showTouches) {
974 mPointerController->clearSpots();
975 }
Michael Wright17db18e2020-06-26 20:51:44 +0100976 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700977 }
978
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700979 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000980 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700981 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000982 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700983 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700984
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700985 configureVirtualKeys();
986
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800987 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700988
989 // Location
990 updateAffineTransformation();
991
Michael Wright227c5542020-07-02 18:30:52 +0100992 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700993 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000994 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
995 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700996
997 // Scale movements such that one whole swipe of the touch pad covers a
998 // given area relative to the diagonal size of the display when no acceleration
999 // is applied.
1000 // Assume that the touch pad has a square aspect ratio such that movements in
1001 // X and Y of the same number of raw units cover the same physical distance.
1002 mPointerXMovementScale =
1003 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1004 mPointerYMovementScale = mPointerXMovementScale;
1005
1006 // Scale zooms to cover a smaller range of the display than movements do.
1007 // This value determines the area around the pointer that is affected by freeform
1008 // pointer gestures.
1009 mPointerXZoomScale =
1010 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1011 mPointerYZoomScale = mPointerXZoomScale;
1012
HQ Liue6983c72022-04-19 22:14:56 +00001013 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1014 // axis is non positive value.
1015 const float minFreeformGestureWidth =
1016 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1017
1018 mPointerGestureMaxSwipeWidth =
1019 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1020 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001021 }
1022
1023 // Inform the dispatcher about the changes.
1024 *outResetNeeded = true;
1025 bumpGeneration();
1026 }
1027}
1028
Prabir Pradhan1728b212021-10-19 16:00:03 -07001029void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001030 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001031 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
1032 dump += StringPrintf(INDENT3 "PhysicalFrame: %s\n", toString(mPhysicalFrameInDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001033 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001034}
1035
1036void TouchInputMapper::configureVirtualKeys() {
1037 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001038 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001039
1040 mVirtualKeys.clear();
1041
1042 if (virtualKeyDefinitions.size() == 0) {
1043 return;
1044 }
1045
1046 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1047 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1048 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1049 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1050
1051 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1052 VirtualKey virtualKey;
1053
1054 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1055 int32_t keyCode;
1056 int32_t dummyKeyMetaState;
1057 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001058 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1059 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001060 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1061 continue; // drop the key
1062 }
1063
1064 virtualKey.keyCode = keyCode;
1065 virtualKey.flags = flags;
1066
1067 // convert the key definition's display coordinates into touch coordinates for a hit box
1068 int32_t halfWidth = virtualKeyDefinition.width / 2;
1069 int32_t halfHeight = virtualKeyDefinition.height / 2;
1070
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001071 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1072 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001073 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001074 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1075 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001076 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001077 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1078 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001079 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001080 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1081 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001082 touchScreenTop;
1083 mVirtualKeys.push_back(virtualKey);
1084 }
1085}
1086
1087void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1088 if (!mVirtualKeys.empty()) {
1089 dump += INDENT3 "Virtual Keys:\n";
1090
1091 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1092 const VirtualKey& virtualKey = mVirtualKeys[i];
1093 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1094 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1095 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1096 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1097 }
1098 }
1099}
1100
1101void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001102 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001103 Calibration& out = mCalibration;
1104
1105 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001106 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001107 std::string sizeCalibrationString;
1108 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001109 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001110 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001111 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001112 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001113 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001114 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001115 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001116 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001117 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001118 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001119 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001120 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001121 }
1122 }
1123
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001124 float sizeScale;
1125
1126 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1127 out.sizeScale = sizeScale;
1128 }
1129 float sizeBias;
1130 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1131 out.sizeBias = sizeBias;
1132 }
1133 bool sizeIsSummed;
1134 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1135 out.sizeIsSummed = sizeIsSummed;
1136 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001137
1138 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001139 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001140 std::string pressureCalibrationString;
1141 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001142 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001143 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001145 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001146 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001147 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001148 } else if (pressureCalibrationString != "default") {
1149 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001150 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001151 }
1152 }
1153
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001154 float pressureScale;
1155 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1156 out.pressureScale = pressureScale;
1157 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001158
1159 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001160 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001161 std::string orientationCalibrationString;
1162 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001163 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001164 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001165 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001166 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001167 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001168 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001169 } else if (orientationCalibrationString != "default") {
1170 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001171 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 }
1173 }
1174
1175 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001176 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001177 std::string distanceCalibrationString;
1178 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001179 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001180 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001181 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001182 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001183 } else if (distanceCalibrationString != "default") {
1184 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001185 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001186 }
1187 }
1188
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001189 float distanceScale;
1190 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1191 out.distanceScale = distanceScale;
1192 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193
Michael Wright227c5542020-07-02 18:30:52 +01001194 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001195 std::string coverageCalibrationString;
1196 if (in.tryGetProperty("touch.coverage.calibration", coverageCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001197 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001198 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001199 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001200 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001201 } else if (coverageCalibrationString != "default") {
1202 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001203 coverageCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001204 }
1205 }
1206}
1207
1208void TouchInputMapper::resolveCalibration() {
1209 // Size
1210 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001211 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1212 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001213 }
1214 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001215 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001216 }
1217
1218 // Pressure
1219 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001220 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1221 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001222 }
1223 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001224 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001225 }
1226
1227 // Orientation
1228 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001229 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1230 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001231 }
1232 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001233 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001234 }
1235
1236 // Distance
1237 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001238 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1239 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001240 }
1241 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001242 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001243 }
1244
1245 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001246 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1247 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248 }
1249}
1250
1251void TouchInputMapper::dumpCalibration(std::string& dump) {
1252 dump += INDENT3 "Calibration:\n";
1253
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001254 dump += INDENT4 "touch.size.calibration: ";
1255 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001256
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001257 if (mCalibration.sizeScale) {
1258 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001259 }
1260
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001261 if (mCalibration.sizeBias) {
1262 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001263 }
1264
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001265 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001266 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001267 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001268 }
1269
1270 // Pressure
1271 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001272 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001273 dump += INDENT4 "touch.pressure.calibration: none\n";
1274 break;
Michael Wright227c5542020-07-02 18:30:52 +01001275 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001276 dump += INDENT4 "touch.pressure.calibration: physical\n";
1277 break;
Michael Wright227c5542020-07-02 18:30:52 +01001278 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001279 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1280 break;
1281 default:
1282 ALOG_ASSERT(false);
1283 }
1284
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001285 if (mCalibration.pressureScale) {
1286 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287 }
1288
1289 // Orientation
1290 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001291 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001292 dump += INDENT4 "touch.orientation.calibration: none\n";
1293 break;
Michael Wright227c5542020-07-02 18:30:52 +01001294 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001295 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1296 break;
Michael Wright227c5542020-07-02 18:30:52 +01001297 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 dump += INDENT4 "touch.orientation.calibration: vector\n";
1299 break;
1300 default:
1301 ALOG_ASSERT(false);
1302 }
1303
1304 // Distance
1305 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001306 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 dump += INDENT4 "touch.distance.calibration: none\n";
1308 break;
Michael Wright227c5542020-07-02 18:30:52 +01001309 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001310 dump += INDENT4 "touch.distance.calibration: scaled\n";
1311 break;
1312 default:
1313 ALOG_ASSERT(false);
1314 }
1315
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001316 if (mCalibration.distanceScale) {
1317 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001318 }
1319
1320 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001321 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001322 dump += INDENT4 "touch.coverage.calibration: none\n";
1323 break;
Michael Wright227c5542020-07-02 18:30:52 +01001324 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001325 dump += INDENT4 "touch.coverage.calibration: box\n";
1326 break;
1327 default:
1328 ALOG_ASSERT(false);
1329 }
1330}
1331
1332void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1333 dump += INDENT3 "Affine Transformation:\n";
1334
1335 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1336 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1337 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1338 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1339 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1340 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1341}
1342
1343void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001344 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001345 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001346}
1347
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001348std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001349 std::list<NotifyArgs> out = cancelTouch(when, when);
1350 updateTouchSpots();
1351
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001352 mCursorButtonAccumulator.reset(getDeviceContext());
1353 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001354 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001355
1356 mPointerVelocityControl.reset();
1357 mWheelXVelocityControl.reset();
1358 mWheelYVelocityControl.reset();
1359
1360 mRawStatesPending.clear();
1361 mCurrentRawState.clear();
1362 mCurrentCookedState.clear();
1363 mLastRawState.clear();
1364 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001365 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001366 mSentHoverEnter = false;
1367 mHavePointerIds = false;
1368 mCurrentMotionAborted = false;
1369 mDownTime = 0;
1370
1371 mCurrentVirtualKey.down = false;
1372
1373 mPointerGesture.reset();
1374 mPointerSimple.reset();
1375 resetExternalStylus();
1376
1377 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001378 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001379 mPointerController->clearSpots();
1380 }
1381
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001382 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001383}
1384
1385void TouchInputMapper::resetExternalStylus() {
1386 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001387 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001388 mExternalStylusFusionTimeout = LLONG_MAX;
1389 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001390 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001391}
1392
1393void TouchInputMapper::clearStylusDataPendingFlags() {
1394 mExternalStylusDataPending = false;
1395 mExternalStylusFusionTimeout = LLONG_MAX;
1396}
1397
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001398std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001399 mCursorButtonAccumulator.process(rawEvent);
1400 mCursorScrollAccumulator.process(rawEvent);
1401 mTouchButtonAccumulator.process(rawEvent);
1402
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001403 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001404 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001405 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001406 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001407 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001408}
1409
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001410std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1411 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001412 if (mDeviceMode == DeviceMode::DISABLED) {
1413 // Only save the last pending state when the device is disabled.
1414 mRawStatesPending.clear();
1415 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001416 // Push a new state.
1417 mRawStatesPending.emplace_back();
1418
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001419 RawState& next = mRawStatesPending.back();
1420 next.clear();
1421 next.when = when;
1422 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001423
1424 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001425 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001426 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1427
1428 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001429 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1430 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001431 mCursorScrollAccumulator.finishSync();
1432
1433 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001434 syncTouch(when, &next);
1435
1436 // The last RawState is the actually second to last, since we just added a new state
1437 const RawState& last =
1438 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001439
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001440 std::tie(next.when, next.readTime) =
1441 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1442 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001443
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001444 // Assign pointer ids.
1445 if (!mHavePointerIds) {
1446 assignPointerIds(last, next);
1447 }
1448
Harry Cutts45483602022-08-24 14:36:48 +00001449 ALOGD_IF(DEBUG_RAW_EVENTS,
1450 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1451 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1452 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1453 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1454 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1455 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001456
Arthur Hung9ad18942021-06-19 02:04:46 +00001457 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1458 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1459 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1460 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1461 next.rawPointerData.hoveringIdBits.value);
1462 }
1463
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001464 out += processRawTouches(false /*timeout*/);
1465 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001466}
1467
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001468std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1469 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001470 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001471 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001472 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001473 }
1474
1475 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1476 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1477 // touching the current state will only observe the events that have been dispatched to the
1478 // rest of the pipeline.
1479 const size_t N = mRawStatesPending.size();
1480 size_t count;
1481 for (count = 0; count < N; count++) {
1482 const RawState& next = mRawStatesPending[count];
1483
1484 // A failure to assign the stylus id means that we're waiting on stylus data
1485 // and so should defer the rest of the pipeline.
1486 if (assignExternalStylusId(next, timeout)) {
1487 break;
1488 }
1489
1490 // All ready to go.
1491 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001492 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001493 if (mCurrentRawState.when < mLastRawState.when) {
1494 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001495 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001496 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001497 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001498 }
1499 if (count != 0) {
1500 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1501 }
1502
1503 if (mExternalStylusDataPending) {
1504 if (timeout) {
1505 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1506 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001507 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001508 ALOGD_IF(DEBUG_STYLUS_FUSION,
1509 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001510 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001511 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001512 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1513 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1514 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1515 }
1516 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001517 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001518}
1519
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001520std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1521 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001522 // Always start with a clean state.
1523 mCurrentCookedState.clear();
1524
1525 // Apply stylus buttons to current raw state.
1526 applyExternalStylusButtonState(when);
1527
1528 // Handle policy on initial down or hover events.
1529 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1530 mCurrentRawState.rawPointerData.pointerCount != 0;
1531
1532 uint32_t policyFlags = 0;
1533 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1534 if (initialDown || buttonsPressed) {
1535 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001536 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001537 getContext()->fadePointer();
1538 }
1539
1540 if (mParameters.wake) {
1541 policyFlags |= POLICY_FLAG_WAKE;
1542 }
1543 }
1544
1545 // Consume raw off-screen touches before cooking pointer data.
1546 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001547 bool consumed;
1548 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1549 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001550 mCurrentRawState.rawPointerData.clear();
1551 }
1552
1553 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1554 // with cooked pointer data that has the same ids and indices as the raw data.
1555 // The following code can use either the raw or cooked data, as needed.
1556 cookPointerData();
1557
1558 // Apply stylus pressure to current cooked state.
1559 applyExternalStylusTouchState(when);
1560
1561 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001562 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1563 mSource, mViewport.displayId, policyFlags,
1564 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001565
1566 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001567 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001568 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1569 uint32_t id = idBits.clearFirstMarkedBit();
1570 const RawPointerData::Pointer& pointer =
1571 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001572 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001573 mCurrentCookedState.stylusIdBits.markBit(id);
1574 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1575 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1576 mCurrentCookedState.fingerIdBits.markBit(id);
1577 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1578 mCurrentCookedState.mouseIdBits.markBit(id);
1579 }
1580 }
1581 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1582 uint32_t id = idBits.clearFirstMarkedBit();
1583 const RawPointerData::Pointer& pointer =
1584 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001585 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001586 mCurrentCookedState.stylusIdBits.markBit(id);
1587 }
1588 }
1589
1590 // Stylus takes precedence over all tools, then mouse, then finger.
1591 PointerUsage pointerUsage = mPointerUsage;
1592 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1593 mCurrentCookedState.mouseIdBits.clear();
1594 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001595 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001596 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1597 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001598 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001599 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1600 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001601 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001602 }
1603
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001604 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001605 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001606 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001607 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001608 out += dispatchButtonRelease(when, readTime, policyFlags);
1609 out += dispatchHoverExit(when, readTime, policyFlags);
1610 out += dispatchTouches(when, readTime, policyFlags);
1611 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1612 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001613 }
1614
1615 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1616 mCurrentMotionAborted = false;
1617 }
1618 }
1619
1620 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001621 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1622 mSource, mViewport.displayId, policyFlags,
1623 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001624
1625 // Clear some transient state.
1626 mCurrentRawState.rawVScroll = 0;
1627 mCurrentRawState.rawHScroll = 0;
1628
1629 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001630 mLastRawState = mCurrentRawState;
1631 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001632 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001633}
1634
Garfield Tanc734e4f2021-01-15 20:01:39 -08001635void TouchInputMapper::updateTouchSpots() {
1636 if (!mConfig.showTouches || mPointerController == nullptr) {
1637 return;
1638 }
1639
1640 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1641 // clear touch spots.
1642 if (mDeviceMode != DeviceMode::DIRECT &&
1643 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1644 return;
1645 }
1646
1647 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1648 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1649
1650 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001651 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1652 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001653 mCurrentCookedState.cookedPointerData.touchingIdBits,
1654 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001655}
1656
1657bool TouchInputMapper::isTouchScreen() {
1658 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1659 mParameters.hasAssociatedDisplay;
1660}
1661
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001662void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001663 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1664 // If any of the external buttons are already pressed by the touch device, ignore them.
1665 const int32_t pressedButtons = ~mCurrentRawState.buttonState & mExternalStylusState.buttons;
1666 const int32_t releasedButtons =
1667 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1668
1669 mCurrentRawState.buttonState |= pressedButtons;
1670 mCurrentRawState.buttonState &= ~releasedButtons;
1671
1672 mExternalStylusButtonsApplied |= pressedButtons;
1673 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001674 }
1675}
1676
1677void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1678 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1679 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001680 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1681 return;
1682 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001683
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001684 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1685 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1686 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1687 : 0.f;
1688 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1689 pressure = *mExternalStylusState.pressure;
1690 }
1691 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1692 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001693
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001694 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001695 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001696 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001697 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001698 }
1699}
1700
1701bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001702 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001703 return false;
1704 }
1705
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001706 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001707 if (mFusedStylusPointerId &&
1708 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001709 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001710 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001711 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001712 }
1713
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001714 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1715 state.rawPointerData.pointerCount != 0;
1716 if (!initialDown) {
1717 return false;
1718 }
1719
1720 if (!mExternalStylusState.pressure) {
1721 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1722 return false;
1723 }
1724
1725 if (*mExternalStylusState.pressure != 0.0f) {
1726 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1727 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1728 return false;
1729 }
1730
1731 if (timeout) {
1732 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1733 mFusedStylusPointerId.reset();
1734 mExternalStylusFusionTimeout = LLONG_MAX;
1735 return false;
1736 }
1737
1738 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1739 // being processed until we either get pressure data or timeout.
1740 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1741 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1742 }
1743 ALOGD_IF(DEBUG_STYLUS_FUSION,
1744 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1745 mExternalStylusFusionTimeout);
1746 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1747 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001748}
1749
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001750std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1751 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001752 if (mDeviceMode == DeviceMode::POINTER) {
1753 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001754 // Since this is a synthetic event, we can consider its latency to be zero
1755 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001756 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001757 }
Michael Wright227c5542020-07-02 18:30:52 +01001758 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001759 if (mExternalStylusFusionTimeout <= when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001760 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001761 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1762 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1763 }
1764 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001765 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001766}
1767
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001768std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1769 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001770 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001771 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001772 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001773 // The following three cases are handled here:
1774 // - We're in the middle of a fused stream of data;
1775 // - We're waiting on external stylus data before dispatching the initial down; or
1776 // - Only the button state, which is not reported through a specific pointer, has changed.
1777 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001778 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001779 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001780 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001781 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001782}
1783
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001784std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1785 uint32_t policyFlags, bool& outConsumed) {
1786 outConsumed = false;
1787 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001788 // Check for release of a virtual key.
1789 if (mCurrentVirtualKey.down) {
1790 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1791 // Pointer went up while virtual key was down.
1792 mCurrentVirtualKey.down = false;
1793 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001794 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1795 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1796 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001797 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1798 AKEY_EVENT_FLAG_FROM_SYSTEM |
1799 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001800 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001801 outConsumed = true;
1802 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001803 }
1804
1805 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1806 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1807 const RawPointerData::Pointer& pointer =
1808 mCurrentRawState.rawPointerData.pointerForId(id);
1809 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1810 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1811 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001812 outConsumed = true;
1813 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001814 }
1815 }
1816
1817 // Pointer left virtual key area or another pointer also went down.
1818 // Send key cancellation but do not consume the touch yet.
1819 // This is useful when the user swipes through from the virtual key area
1820 // into the main display surface.
1821 mCurrentVirtualKey.down = false;
1822 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001823 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1824 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001825 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1826 AKEY_EVENT_FLAG_FROM_SYSTEM |
1827 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1828 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001829 }
1830 }
1831
1832 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1833 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1834 // Pointer just went down. Check for virtual key press or off-screen touches.
1835 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1836 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001837 // Skip checking whether the pointer is inside the physical frame if the device is in
1838 // unscaled mode.
1839 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1840 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001841 // If exactly one pointer went down, check for virtual key hit.
1842 // Otherwise we will drop the entire stroke.
1843 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1844 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1845 if (virtualKey) {
1846 mCurrentVirtualKey.down = true;
1847 mCurrentVirtualKey.downTime = when;
1848 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1849 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1850 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001851 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1852 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001853
1854 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001855 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1856 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1857 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001858 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1859 AKEY_EVENT_ACTION_DOWN,
1860 AKEY_EVENT_FLAG_FROM_SYSTEM |
1861 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001862 }
1863 }
1864 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001865 outConsumed = true;
1866 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001867 }
1868 }
1869
1870 // Disable all virtual key touches that happen within a short time interval of the
1871 // most recent touch within the screen area. The idea is to filter out stray
1872 // virtual key presses when interacting with the touch screen.
1873 //
1874 // Problems we're trying to solve:
1875 //
1876 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1877 // virtual key area that is implemented by a separate touch panel and accidentally
1878 // triggers a virtual key.
1879 //
1880 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1881 // area and accidentally triggers a virtual key. This often happens when virtual keys
1882 // are layed out below the screen near to where the on screen keyboard's space bar
1883 // is displayed.
1884 if (mConfig.virtualKeyQuietTime > 0 &&
1885 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001886 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001887 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001888 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001889}
1890
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001891NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1892 uint32_t policyFlags, int32_t keyEventAction,
1893 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001894 int32_t keyCode = mCurrentVirtualKey.keyCode;
1895 int32_t scanCode = mCurrentVirtualKey.scanCode;
1896 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001897 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001898 policyFlags |= POLICY_FLAG_VIRTUAL;
1899
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001900 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1901 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1902 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001903}
1904
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001905std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1906 uint32_t policyFlags) {
1907 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001908 if (mCurrentMotionAborted) {
1909 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001910 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001911 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001912 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1913 if (!currentIdBits.isEmpty()) {
1914 int32_t metaState = getContext()->getGlobalMetaState();
1915 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001916 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001917 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1918 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001919 mCurrentCookedState.cookedPointerData.pointerProperties,
1920 mCurrentCookedState.cookedPointerData.pointerCoords,
1921 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1922 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1923 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001924 mCurrentMotionAborted = true;
1925 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001926 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001927}
1928
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001929// Updates pointer coords and properties for pointers with specified ids that have moved.
1930// Returns true if any of them changed.
1931static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1932 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1933 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1934 BitSet32 idBits) {
1935 bool changed = false;
1936 while (!idBits.isEmpty()) {
1937 uint32_t id = idBits.clearFirstMarkedBit();
1938 uint32_t inIndex = inIdToIndex[id];
1939 uint32_t outIndex = outIdToIndex[id];
1940
1941 const PointerProperties& curInProperties = inProperties[inIndex];
1942 const PointerCoords& curInCoords = inCoords[inIndex];
1943 PointerProperties& curOutProperties = outProperties[outIndex];
1944 PointerCoords& curOutCoords = outCoords[outIndex];
1945
1946 if (curInProperties != curOutProperties) {
1947 curOutProperties.copyFrom(curInProperties);
1948 changed = true;
1949 }
1950
1951 if (curInCoords != curOutCoords) {
1952 curOutCoords.copyFrom(curInCoords);
1953 changed = true;
1954 }
1955 }
1956 return changed;
1957}
1958
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001959std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1960 uint32_t policyFlags) {
1961 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001962 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1963 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1964 int32_t metaState = getContext()->getGlobalMetaState();
1965 int32_t buttonState = mCurrentCookedState.buttonState;
1966
1967 if (currentIdBits == lastIdBits) {
1968 if (!currentIdBits.isEmpty()) {
1969 // No pointer id changes so this is a move event.
1970 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001971 out.push_back(
1972 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1973 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1974 mCurrentCookedState.cookedPointerData.pointerProperties,
1975 mCurrentCookedState.cookedPointerData.pointerCoords,
1976 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1977 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1978 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001979 }
1980 } else {
1981 // There may be pointers going up and pointers going down and pointers moving
1982 // all at the same time.
1983 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1984 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1985 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1986 BitSet32 dispatchedIdBits(lastIdBits.value);
1987
1988 // Update last coordinates of pointers that have moved so that we observe the new
1989 // pointer positions at the same time as other pointers that have just gone up.
1990 bool moveNeeded =
1991 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1992 mCurrentCookedState.cookedPointerData.pointerCoords,
1993 mCurrentCookedState.cookedPointerData.idToIndex,
1994 mLastCookedState.cookedPointerData.pointerProperties,
1995 mLastCookedState.cookedPointerData.pointerCoords,
1996 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1997 if (buttonState != mLastCookedState.buttonState) {
1998 moveNeeded = true;
1999 }
2000
2001 // Dispatch pointer up events.
2002 while (!upIdBits.isEmpty()) {
2003 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08002004 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08002005 if (isCanceled) {
2006 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
2007 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002008 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2009 AMOTION_EVENT_ACTION_POINTER_UP, 0,
2010 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
2011 buttonState, 0,
2012 mLastCookedState.cookedPointerData.pointerProperties,
2013 mLastCookedState.cookedPointerData.pointerCoords,
2014 mLastCookedState.cookedPointerData.idToIndex,
2015 dispatchedIdBits, upId, mOrientedXPrecision,
2016 mOrientedYPrecision, mDownTime,
2017 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002018 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002019 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002020 }
2021
2022 // Dispatch move events if any of the remaining pointers moved from their old locations.
2023 // Although applications receive new locations as part of individual pointer up
2024 // events, they do not generally handle them except when presented in a move event.
2025 if (moveNeeded && !moveIdBits.isEmpty()) {
2026 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002027 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2028 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2029 mCurrentCookedState.cookedPointerData.pointerProperties,
2030 mCurrentCookedState.cookedPointerData.pointerCoords,
2031 mCurrentCookedState.cookedPointerData.idToIndex,
2032 dispatchedIdBits, -1, mOrientedXPrecision,
2033 mOrientedYPrecision, mDownTime,
2034 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002035 }
2036
2037 // Dispatch pointer down events using the new pointer locations.
2038 while (!downIdBits.isEmpty()) {
2039 uint32_t downId = downIdBits.clearFirstMarkedBit();
2040 dispatchedIdBits.markBit(downId);
2041
2042 if (dispatchedIdBits.count() == 1) {
2043 // First pointer is going down. Set down time.
2044 mDownTime = when;
2045 }
2046
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002047 out.push_back(
2048 dispatchMotion(when, readTime, policyFlags, mSource,
2049 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2050 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2051 mCurrentCookedState.cookedPointerData.pointerCoords,
2052 mCurrentCookedState.cookedPointerData.idToIndex,
2053 dispatchedIdBits, downId, mOrientedXPrecision,
2054 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002055 }
2056 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002057 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002058}
2059
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002060std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2061 uint32_t policyFlags) {
2062 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002063 if (mSentHoverEnter &&
2064 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2065 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2066 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002067 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2068 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2069 mLastCookedState.buttonState, 0,
2070 mLastCookedState.cookedPointerData.pointerProperties,
2071 mLastCookedState.cookedPointerData.pointerCoords,
2072 mLastCookedState.cookedPointerData.idToIndex,
2073 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2074 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2075 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002076 mSentHoverEnter = false;
2077 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002078 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002079}
2080
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002081std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2082 uint32_t policyFlags) {
2083 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002084 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2085 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2086 int32_t metaState = getContext()->getGlobalMetaState();
2087 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002088 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2089 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2090 mCurrentRawState.buttonState, 0,
2091 mCurrentCookedState.cookedPointerData.pointerProperties,
2092 mCurrentCookedState.cookedPointerData.pointerCoords,
2093 mCurrentCookedState.cookedPointerData.idToIndex,
2094 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2095 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2096 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002097 mSentHoverEnter = true;
2098 }
2099
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002100 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2101 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2102 mCurrentRawState.buttonState, 0,
2103 mCurrentCookedState.cookedPointerData.pointerProperties,
2104 mCurrentCookedState.cookedPointerData.pointerCoords,
2105 mCurrentCookedState.cookedPointerData.idToIndex,
2106 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2107 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2108 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002109 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002110 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002111}
2112
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002113std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2114 uint32_t policyFlags) {
2115 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002116 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2117 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2118 const int32_t metaState = getContext()->getGlobalMetaState();
2119 int32_t buttonState = mLastCookedState.buttonState;
2120 while (!releasedButtons.isEmpty()) {
2121 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2122 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002123 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2124 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2125 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002126 mLastCookedState.cookedPointerData.pointerProperties,
2127 mLastCookedState.cookedPointerData.pointerCoords,
2128 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002129 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2130 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002131 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002132 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002133}
2134
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002135std::list<NotifyArgs> TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2136 uint32_t policyFlags) {
2137 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002138 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2139 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2140 const int32_t metaState = getContext()->getGlobalMetaState();
2141 int32_t buttonState = mLastCookedState.buttonState;
2142 while (!pressedButtons.isEmpty()) {
2143 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2144 buttonState |= actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002145 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2146 AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState,
2147 buttonState, 0,
2148 mCurrentCookedState.cookedPointerData.pointerProperties,
2149 mCurrentCookedState.cookedPointerData.pointerCoords,
2150 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2151 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2152 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002153 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002154 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002155}
2156
2157const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2158 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2159 return cookedPointerData.touchingIdBits;
2160 }
2161 return cookedPointerData.hoveringIdBits;
2162}
2163
2164void TouchInputMapper::cookPointerData() {
2165 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2166
2167 mCurrentCookedState.cookedPointerData.clear();
2168 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2169 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2170 mCurrentRawState.rawPointerData.hoveringIdBits;
2171 mCurrentCookedState.cookedPointerData.touchingIdBits =
2172 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002173 mCurrentCookedState.cookedPointerData.canceledIdBits =
2174 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002175
2176 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2177 mCurrentCookedState.buttonState = 0;
2178 } else {
2179 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2180 }
2181
2182 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002183 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002184 for (uint32_t i = 0; i < currentPointerCount; i++) {
2185 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2186
2187 // Size
2188 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2189 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002190 case Calibration::SizeCalibration::GEOMETRIC:
2191 case Calibration::SizeCalibration::DIAMETER:
2192 case Calibration::SizeCalibration::BOX:
2193 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002194 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2195 touchMajor = in.touchMajor;
2196 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2197 toolMajor = in.toolMajor;
2198 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2199 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2200 : in.touchMajor;
2201 } else if (mRawPointerAxes.touchMajor.valid) {
2202 toolMajor = touchMajor = in.touchMajor;
2203 toolMinor = touchMinor =
2204 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2205 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2206 : in.touchMajor;
2207 } else if (mRawPointerAxes.toolMajor.valid) {
2208 touchMajor = toolMajor = in.toolMajor;
2209 touchMinor = toolMinor =
2210 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2211 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2212 : in.toolMajor;
2213 } else {
2214 ALOG_ASSERT(false,
2215 "No touch or tool axes. "
2216 "Size calibration should have been resolved to NONE.");
2217 touchMajor = 0;
2218 touchMinor = 0;
2219 toolMajor = 0;
2220 toolMinor = 0;
2221 size = 0;
2222 }
2223
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002224 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002225 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2226 if (touchingCount > 1) {
2227 touchMajor /= touchingCount;
2228 touchMinor /= touchingCount;
2229 toolMajor /= touchingCount;
2230 toolMinor /= touchingCount;
2231 size /= touchingCount;
2232 }
2233 }
2234
Michael Wright227c5542020-07-02 18:30:52 +01002235 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002236 touchMajor *= mGeometricScale;
2237 touchMinor *= mGeometricScale;
2238 toolMajor *= mGeometricScale;
2239 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002240 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002241 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2242 touchMinor = touchMajor;
2243 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2244 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002245 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002246 touchMinor = touchMajor;
2247 toolMinor = toolMajor;
2248 }
2249
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002250 mCalibration.applySizeScaleAndBias(touchMajor);
2251 mCalibration.applySizeScaleAndBias(touchMinor);
2252 mCalibration.applySizeScaleAndBias(toolMajor);
2253 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002254 size *= mSizeScale;
2255 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002256 case Calibration::SizeCalibration::DEFAULT:
2257 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2258 break;
2259 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002260 touchMajor = 0;
2261 touchMinor = 0;
2262 toolMajor = 0;
2263 toolMinor = 0;
2264 size = 0;
2265 break;
2266 }
2267
2268 // Pressure
2269 float pressure;
2270 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002271 case Calibration::PressureCalibration::PHYSICAL:
2272 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002273 pressure = in.pressure * mPressureScale;
2274 break;
2275 default:
2276 pressure = in.isHovering ? 0 : 1;
2277 break;
2278 }
2279
2280 // Tilt and Orientation
2281 float tilt;
2282 float orientation;
2283 if (mHaveTilt) {
2284 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2285 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2286 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2287 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2288 } else {
2289 tilt = 0;
2290
2291 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002292 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002293 orientation = in.orientation * mOrientationScale;
2294 break;
Michael Wright227c5542020-07-02 18:30:52 +01002295 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002296 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2297 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2298 if (c1 != 0 || c2 != 0) {
2299 orientation = atan2f(c1, c2) * 0.5f;
2300 float confidence = hypotf(c1, c2);
2301 float scale = 1.0f + confidence / 16.0f;
2302 touchMajor *= scale;
2303 touchMinor /= scale;
2304 toolMajor *= scale;
2305 toolMinor /= scale;
2306 } else {
2307 orientation = 0;
2308 }
2309 break;
2310 }
2311 default:
2312 orientation = 0;
2313 }
2314 }
2315
2316 // Distance
2317 float distance;
2318 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002319 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002320 distance = in.distance * mDistanceScale;
2321 break;
2322 default:
2323 distance = 0;
2324 }
2325
2326 // Coverage
2327 int32_t rawLeft, rawTop, rawRight, rawBottom;
2328 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002329 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002330 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2331 rawRight = in.toolMinor & 0x0000ffff;
2332 rawBottom = in.toolMajor & 0x0000ffff;
2333 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2334 break;
2335 default:
2336 rawLeft = rawTop = rawRight = rawBottom = 0;
2337 break;
2338 }
2339
2340 // Adjust X,Y coords for device calibration
2341 // TODO: Adjust coverage coords?
2342 float xTransformed = in.x, yTransformed = in.y;
2343 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002344 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002345
Prabir Pradhan1728b212021-10-19 16:00:03 -07002346 // Adjust X, Y, and coverage coords for input device orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002347 float left, top, right, bottom;
2348
Prabir Pradhan1728b212021-10-19 16:00:03 -07002349 switch (mInputDeviceOrientation) {
Michael Wrighta9cf4192022-12-01 23:46:39 +00002350 case ui::ROTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002351 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
2352 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2353 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2354 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002355 orientation -= M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002356 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002357 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002358 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002359 }
2360 break;
Michael Wrighta9cf4192022-12-01 23:46:39 +00002361 case ui::ROTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002362 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2363 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002364 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2365 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002366 orientation -= M_PI;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002367 if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002368 orientation +=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002369 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002370 }
2371 break;
Michael Wrighta9cf4192022-12-01 23:46:39 +00002372 case ui::ROTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002373 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2374 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002375 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2376 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002377 orientation += M_PI_2;
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002378 if (mOrientedRanges.orientation && orientation > mOrientedRanges.orientation->max) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002379 orientation -=
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002380 (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002381 }
2382 break;
2383 default:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002384 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
2385 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2386 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2387 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002388 break;
2389 }
2390
2391 // Write output coords.
2392 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2393 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002394 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2395 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002396 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2397 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2398 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2399 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2400 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2401 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2402 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002403 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002404 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2405 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2406 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2407 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2408 } else {
2409 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2410 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2411 }
2412
Chris Ye364fdb52020-08-05 15:07:56 -07002413 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002414 uint32_t id = in.id;
2415 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2416 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2417 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2418 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2419 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2420 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2421 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2422 }
2423
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002424 // Write output properties.
2425 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002426 properties.clear();
2427 properties.id = id;
2428 properties.toolType = in.toolType;
2429
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002430 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002431 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002432 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002433 }
2434}
2435
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002436std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2437 uint32_t policyFlags,
2438 PointerUsage pointerUsage) {
2439 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002440 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002441 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002442 mPointerUsage = pointerUsage;
2443 }
2444
2445 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002446 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002447 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002448 break;
Michael Wright227c5542020-07-02 18:30:52 +01002449 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002450 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002451 break;
Michael Wright227c5542020-07-02 18:30:52 +01002452 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002453 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002454 break;
Michael Wright227c5542020-07-02 18:30:52 +01002455 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002456 break;
2457 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002458 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002459}
2460
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002461std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2462 uint32_t policyFlags) {
2463 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002464 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002465 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002466 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002467 break;
Michael Wright227c5542020-07-02 18:30:52 +01002468 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002469 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002470 break;
Michael Wright227c5542020-07-02 18:30:52 +01002471 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002472 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002473 break;
Michael Wright227c5542020-07-02 18:30:52 +01002474 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002475 break;
2476 }
2477
Michael Wright227c5542020-07-02 18:30:52 +01002478 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002479 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002480}
2481
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002482std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2483 uint32_t policyFlags,
2484 bool isTimeout) {
2485 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002486 // Update current gesture coordinates.
2487 bool cancelPreviousGesture, finishPreviousGesture;
2488 bool sendEvents =
2489 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2490 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002491 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002492 }
2493 if (finishPreviousGesture) {
2494 cancelPreviousGesture = false;
2495 }
2496
2497 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002498 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002499 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002500 if (finishPreviousGesture || cancelPreviousGesture) {
2501 mPointerController->clearSpots();
2502 }
2503
Michael Wright227c5542020-07-02 18:30:52 +01002504 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002505 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2506 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002507 mPointerGesture.currentGestureIdBits,
2508 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002509 }
2510 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002511 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002512 }
2513
2514 // Show or hide the pointer if needed.
2515 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002516 case PointerGesture::Mode::NEUTRAL:
2517 case PointerGesture::Mode::QUIET:
2518 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2519 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002520 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002521 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002522 }
2523 break;
Michael Wright227c5542020-07-02 18:30:52 +01002524 case PointerGesture::Mode::TAP:
2525 case PointerGesture::Mode::TAP_DRAG:
2526 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2527 case PointerGesture::Mode::HOVER:
2528 case PointerGesture::Mode::PRESS:
2529 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002530 // Unfade the pointer when the current gesture manipulates the
2531 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002532 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002533 break;
Michael Wright227c5542020-07-02 18:30:52 +01002534 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002535 // Fade the pointer when the current gesture manipulates a different
2536 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002537 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002538 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002539 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002540 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002541 }
2542 break;
2543 }
2544
2545 // Send events!
2546 int32_t metaState = getContext()->getGlobalMetaState();
2547 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002548 const MotionClassification classification =
2549 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2550 ? MotionClassification::TWO_FINGER_SWIPE
2551 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002552
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002553 uint32_t flags = 0;
2554
2555 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2556 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2557 }
2558
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002559 // Update last coordinates of pointers that have moved so that we observe the new
2560 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002561 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2562 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2563 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2564 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2565 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2566 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002567 bool moveNeeded = false;
2568 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2569 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2570 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2571 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2572 mPointerGesture.lastGestureIdBits.value);
2573 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2574 mPointerGesture.currentGestureCoords,
2575 mPointerGesture.currentGestureIdToIndex,
2576 mPointerGesture.lastGestureProperties,
2577 mPointerGesture.lastGestureCoords,
2578 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2579 if (buttonState != mLastCookedState.buttonState) {
2580 moveNeeded = true;
2581 }
2582 }
2583
2584 // Send motion events for all pointers that went up or were canceled.
2585 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2586 if (!dispatchedGestureIdBits.isEmpty()) {
2587 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002588 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002589 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002590 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002591 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2592 mPointerGesture.lastGestureProperties,
2593 mPointerGesture.lastGestureCoords,
2594 mPointerGesture.lastGestureIdToIndex,
2595 dispatchedGestureIdBits, -1, 0, 0,
2596 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002597
2598 dispatchedGestureIdBits.clear();
2599 } else {
2600 BitSet32 upGestureIdBits;
2601 if (finishPreviousGesture) {
2602 upGestureIdBits = dispatchedGestureIdBits;
2603 } else {
2604 upGestureIdBits.value =
2605 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2606 }
2607 while (!upGestureIdBits.isEmpty()) {
2608 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2609
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002610 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2611 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2612 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2613 mPointerGesture.lastGestureProperties,
2614 mPointerGesture.lastGestureCoords,
2615 mPointerGesture.lastGestureIdToIndex,
2616 dispatchedGestureIdBits, id, 0, 0,
2617 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002618
2619 dispatchedGestureIdBits.clearBit(id);
2620 }
2621 }
2622 }
2623
2624 // Send motion events for all pointers that moved.
2625 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002626 out.push_back(
2627 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2628 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2629 mPointerGesture.currentGestureProperties,
2630 mPointerGesture.currentGestureCoords,
2631 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2632 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002633 }
2634
2635 // Send motion events for all pointers that went down.
2636 if (down) {
2637 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2638 ~dispatchedGestureIdBits.value);
2639 while (!downGestureIdBits.isEmpty()) {
2640 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2641 dispatchedGestureIdBits.markBit(id);
2642
2643 if (dispatchedGestureIdBits.count() == 1) {
2644 mPointerGesture.downTime = when;
2645 }
2646
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002647 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2648 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2649 buttonState, 0, mPointerGesture.currentGestureProperties,
2650 mPointerGesture.currentGestureCoords,
2651 mPointerGesture.currentGestureIdToIndex,
2652 dispatchedGestureIdBits, id, 0, 0,
2653 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002654 }
2655 }
2656
2657 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002658 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002659 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2660 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2661 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2662 mPointerGesture.currentGestureProperties,
2663 mPointerGesture.currentGestureCoords,
2664 mPointerGesture.currentGestureIdToIndex,
2665 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2666 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002667 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2668 // Synthesize a hover move event after all pointers go up to indicate that
2669 // the pointer is hovering again even if the user is not currently touching
2670 // the touch pad. This ensures that a view will receive a fresh hover enter
2671 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002672 float x, y;
2673 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002674
2675 PointerProperties pointerProperties;
2676 pointerProperties.clear();
2677 pointerProperties.id = 0;
2678 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2679
2680 PointerCoords pointerCoords;
2681 pointerCoords.clear();
2682 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2683 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2684
2685 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002686 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2687 mSource, displayId, policyFlags,
2688 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2689 buttonState, MotionClassification::NONE,
2690 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2691 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2692 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002693 }
2694
2695 // Update state.
2696 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2697 if (!down) {
2698 mPointerGesture.lastGestureIdBits.clear();
2699 } else {
2700 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2701 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2702 uint32_t id = idBits.clearFirstMarkedBit();
2703 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2704 mPointerGesture.lastGestureProperties[index].copyFrom(
2705 mPointerGesture.currentGestureProperties[index]);
2706 mPointerGesture.lastGestureCoords[index].copyFrom(
2707 mPointerGesture.currentGestureCoords[index]);
2708 mPointerGesture.lastGestureIdToIndex[id] = index;
2709 }
2710 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002711 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002712}
2713
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002714std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2715 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002716 const MotionClassification classification =
2717 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2718 ? MotionClassification::TWO_FINGER_SWIPE
2719 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002720 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002721 // Cancel previously dispatches pointers.
2722 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2723 int32_t metaState = getContext()->getGlobalMetaState();
2724 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002725 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002726 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2727 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002728 mPointerGesture.lastGestureProperties,
2729 mPointerGesture.lastGestureCoords,
2730 mPointerGesture.lastGestureIdToIndex,
2731 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2732 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002733 }
2734
2735 // Reset the current pointer gesture.
2736 mPointerGesture.reset();
2737 mPointerVelocityControl.reset();
2738
2739 // Remove any current spots.
2740 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002741 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002742 mPointerController->clearSpots();
2743 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002744 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002745}
2746
2747bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2748 bool* outFinishPreviousGesture, bool isTimeout) {
2749 *outCancelPreviousGesture = false;
2750 *outFinishPreviousGesture = false;
2751
2752 // Handle TAP timeout.
2753 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002754 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002755
Michael Wright227c5542020-07-02 18:30:52 +01002756 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002757 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2758 // The tap/drag timeout has not yet expired.
2759 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2760 mConfig.pointerGestureTapDragInterval);
2761 } else {
2762 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002763 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002764 *outFinishPreviousGesture = true;
2765
2766 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002767 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002768 mPointerGesture.currentGestureIdBits.clear();
2769
2770 mPointerVelocityControl.reset();
2771 return true;
2772 }
2773 }
2774
2775 // We did not handle this timeout.
2776 return false;
2777 }
2778
2779 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2780 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2781
2782 // Update the velocity tracker.
2783 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002784 std::vector<float> positionsX;
2785 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002786 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002787 uint32_t id = idBits.clearFirstMarkedBit();
2788 const RawPointerData::Pointer& pointer =
2789 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002790 positionsX.push_back(pointer.x * mPointerXMovementScale);
2791 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002792 }
2793 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002794 {{AMOTION_EVENT_AXIS_X, positionsX},
2795 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002796 }
2797
2798 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2799 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002800 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2801 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2802 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002803 mPointerGesture.resetTap();
2804 }
2805
2806 // Pick a new active touch id if needed.
2807 // Choose an arbitrary pointer that just went down, if there is one.
2808 // Otherwise choose an arbitrary remaining pointer.
2809 // This guarantees we always have an active touch id when there is at least one pointer.
2810 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002811 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002812 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002813 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002814 mPointerGesture.firstTouchTime = when;
2815 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002816 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2817 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2818 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2819 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002820 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002821 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002822
2823 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002824 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002825 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002826 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2827 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2828 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002829 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002830 *outFinishPreviousGesture = true;
2831 }
2832
2833 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002834 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002835 mPointerGesture.currentGestureIdBits.clear();
2836
2837 mPointerVelocityControl.reset();
2838 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2839 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2840 // The pointer follows the active touch point.
2841 // Emit DOWN, MOVE, UP events at the pointer location.
2842 //
2843 // Only the active touch matters; other fingers are ignored. This policy helps
2844 // to handle the case where the user places a second finger on the touch pad
2845 // to apply the necessary force to depress an integrated button below the surface.
2846 // We don't want the second finger to be delivered to applications.
2847 //
2848 // For this to work well, we need to make sure to track the pointer that is really
2849 // active. If the user first puts one finger down to click then adds another
2850 // finger to drag then the active pointer should switch to the finger that is
2851 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002852 ALOGD_IF(DEBUG_GESTURES,
2853 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2854 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002855 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002856 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002857 *outFinishPreviousGesture = true;
2858 mPointerGesture.activeGestureId = 0;
2859 }
2860
2861 // Switch pointers if needed.
2862 // Find the fastest pointer and follow it.
2863 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002864 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002865 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002866 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002867 ALOGD_IF(DEBUG_GESTURES,
2868 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2869 "bestSpeed=%0.3f",
2870 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002871 }
2872 }
2873
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002874 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002875 // When using spots, the click will occur at the position of the anchor
2876 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002877 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002878 } else {
2879 mPointerVelocityControl.reset();
2880 }
2881
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002882 float x, y;
2883 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002884
Michael Wright227c5542020-07-02 18:30:52 +01002885 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002886 mPointerGesture.currentGestureIdBits.clear();
2887 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2888 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2889 mPointerGesture.currentGestureProperties[0].clear();
2890 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2891 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2892 mPointerGesture.currentGestureCoords[0].clear();
2893 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2894 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2895 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2896 } else if (currentFingerCount == 0) {
2897 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002898 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002899 *outFinishPreviousGesture = true;
2900 }
2901
2902 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2903 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2904 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002905 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2906 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002907 lastFingerCount == 1) {
2908 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002909 float x, y;
2910 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002911 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2912 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002913 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002914
2915 mPointerGesture.tapUpTime = when;
2916 getContext()->requestTimeoutAtTime(when +
2917 mConfig.pointerGestureTapDragInterval);
2918
2919 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002920 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002921 mPointerGesture.currentGestureIdBits.clear();
2922 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2923 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2924 mPointerGesture.currentGestureProperties[0].clear();
2925 mPointerGesture.currentGestureProperties[0].id =
2926 mPointerGesture.activeGestureId;
2927 mPointerGesture.currentGestureProperties[0].toolType =
2928 AMOTION_EVENT_TOOL_TYPE_FINGER;
2929 mPointerGesture.currentGestureCoords[0].clear();
2930 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2931 mPointerGesture.tapX);
2932 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2933 mPointerGesture.tapY);
2934 mPointerGesture.currentGestureCoords[0]
2935 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2936
2937 tapped = true;
2938 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002939 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2940 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002941 }
2942 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002943 if (DEBUG_GESTURES) {
2944 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2945 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2946 (when - mPointerGesture.tapDownTime) * 0.000001f);
2947 } else {
2948 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2949 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002950 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002951 }
2952 }
2953
2954 mPointerVelocityControl.reset();
2955
2956 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002957 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002958 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002959 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002960 mPointerGesture.currentGestureIdBits.clear();
2961 }
2962 } else if (currentFingerCount == 1) {
2963 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2964 // The pointer follows the active touch point.
2965 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2966 // When in TAP_DRAG, emit MOVE events at the pointer location.
2967 ALOG_ASSERT(activeTouchId >= 0);
2968
Michael Wright227c5542020-07-02 18:30:52 +01002969 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2970 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002971 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002972 float x, y;
2973 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002974 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2975 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002976 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002977 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002978 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2979 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002980 }
2981 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002982 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2983 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002984 }
Michael Wright227c5542020-07-02 18:30:52 +01002985 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2986 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002987 }
2988
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002989 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002990 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002991 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002992 } else {
2993 mPointerVelocityControl.reset();
2994 }
2995
2996 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002997 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00002998 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002999 down = true;
3000 } else {
Harry Cutts45483602022-08-24 14:36:48 +00003001 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01003002 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003003 *outFinishPreviousGesture = true;
3004 }
3005 mPointerGesture.activeGestureId = 0;
3006 down = false;
3007 }
3008
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003009 float x, y;
3010 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003011
3012 mPointerGesture.currentGestureIdBits.clear();
3013 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3014 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3015 mPointerGesture.currentGestureProperties[0].clear();
3016 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3017 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3018 mPointerGesture.currentGestureCoords[0].clear();
3019 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3020 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3021 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3022 down ? 1.0f : 0.0f);
3023
3024 if (lastFingerCount == 0 && currentFingerCount != 0) {
3025 mPointerGesture.resetTap();
3026 mPointerGesture.tapDownTime = when;
3027 mPointerGesture.tapX = x;
3028 mPointerGesture.tapY = y;
3029 }
3030 } else {
3031 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003032 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003033 }
3034
3035 mPointerController->setButtonState(mCurrentRawState.buttonState);
3036
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003037 if (DEBUG_GESTURES) {
3038 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3039 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3040 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3041 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3042 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3043 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3044 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3045 uint32_t id = idBits.clearFirstMarkedBit();
3046 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3047 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3048 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3049 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3050 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3051 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3052 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3053 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3054 }
3055 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3056 uint32_t id = idBits.clearFirstMarkedBit();
3057 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3058 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3059 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3060 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3061 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3062 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3063 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3064 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3065 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003066 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003067 return true;
3068}
3069
Harry Cuttsbea6ce52022-10-14 15:17:30 +00003070bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
3071 if (mPointerGesture.activeTouchId < 0) {
3072 mPointerGesture.resetQuietTime();
3073 return false;
3074 }
3075
3076 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
3077 return true;
3078 }
3079
3080 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3081 bool isQuietTime = false;
3082 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
3083 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
3084 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
3085 currentFingerCount < 2) {
3086 // Enter quiet time when exiting swipe or freeform state.
3087 // This is to prevent accidentally entering the hover state and flinging the
3088 // pointer when finishing a swipe and there is still one pointer left onscreen.
3089 isQuietTime = true;
3090 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3091 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3092 // Enter quiet time when releasing the button and there are still two or more
3093 // fingers down. This may indicate that one finger was used to press the button
3094 // but it has not gone up yet.
3095 isQuietTime = true;
3096 }
3097 if (isQuietTime) {
3098 mPointerGesture.quietTime = when;
3099 }
3100 return isQuietTime;
3101}
3102
3103std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3104 int32_t bestId = -1;
3105 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3106 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3107 uint32_t id = idBits.clearFirstMarkedBit();
3108 std::optional<float> vx =
3109 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3110 std::optional<float> vy =
3111 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3112 if (vx && vy) {
3113 float speed = hypotf(*vx, *vy);
3114 if (speed > bestSpeed) {
3115 bestId = id;
3116 bestSpeed = speed;
3117 }
3118 }
3119 }
3120 return std::make_pair(bestId, bestSpeed);
3121}
3122
3123void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3124 bool* finishPreviousGesture) {
3125 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3126 // to move before deciding what to do.
3127 //
3128 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3129 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3130 // just a press or long-press at the pointer location.
3131 //
3132 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3133 // pointer location.
3134 //
3135 // When the two fingers move enough or when additional fingers are added, we make a decision to
3136 // transition into SWIPE or FREEFORM mode accordingly.
3137 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3138 ALOG_ASSERT(activeTouchId >= 0);
3139
3140 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3141 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3142 bool settled =
3143 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3144 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3145 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3146 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3147 *finishPreviousGesture = true;
3148 } else if (!settled && currentFingerCount > lastFingerCount) {
3149 // Additional pointers have gone down but not yet settled.
3150 // Reset the gesture.
3151 ALOGD_IF(DEBUG_GESTURES,
3152 "Gestures: Resetting gesture since additional pointers went down for "
3153 "MULTITOUCH, settle time remaining %0.3fms",
3154 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3155 when) * 0.000001f);
3156 *cancelPreviousGesture = true;
3157 } else {
3158 // Continue previous gesture.
3159 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3160 }
3161
3162 if (*finishPreviousGesture || *cancelPreviousGesture) {
3163 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3164 mPointerGesture.activeGestureId = 0;
3165 mPointerGesture.referenceIdBits.clear();
3166 mPointerVelocityControl.reset();
3167
3168 // Use the centroid and pointer location as the reference points for the gesture.
3169 ALOGD_IF(DEBUG_GESTURES,
3170 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3171 "%0.3fms",
3172 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3173 when) * 0.000001f);
3174 mCurrentRawState.rawPointerData
3175 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3176 &mPointerGesture.referenceTouchY);
3177 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3178 &mPointerGesture.referenceGestureY);
3179 }
3180
3181 // Clear the reference deltas for fingers not yet included in the reference calculation.
3182 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3183 ~mPointerGesture.referenceIdBits.value);
3184 !idBits.isEmpty();) {
3185 uint32_t id = idBits.clearFirstMarkedBit();
3186 mPointerGesture.referenceDeltas[id].dx = 0;
3187 mPointerGesture.referenceDeltas[id].dy = 0;
3188 }
3189 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3190
3191 // Add delta for all fingers and calculate a common movement delta.
3192 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3193 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3194 mCurrentCookedState.fingerIdBits.value);
3195 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3196 bool first = (idBits == commonIdBits);
3197 uint32_t id = idBits.clearFirstMarkedBit();
3198 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3199 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3200 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3201 delta.dx += cpd.x - lpd.x;
3202 delta.dy += cpd.y - lpd.y;
3203
3204 if (first) {
3205 commonDeltaRawX = delta.dx;
3206 commonDeltaRawY = delta.dy;
3207 } else {
3208 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3209 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3210 }
3211 }
3212
3213 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3214 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3215 float dist[MAX_POINTER_ID + 1];
3216 int32_t distOverThreshold = 0;
3217 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3218 uint32_t id = idBits.clearFirstMarkedBit();
3219 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3220 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3221 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3222 distOverThreshold += 1;
3223 }
3224 }
3225
3226 // Only transition when at least two pointers have moved further than
3227 // the minimum distance threshold.
3228 if (distOverThreshold >= 2) {
3229 if (currentFingerCount > 2) {
3230 // There are more than two pointers, switch to FREEFORM.
3231 ALOGD_IF(DEBUG_GESTURES,
3232 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3233 currentFingerCount);
3234 *cancelPreviousGesture = true;
3235 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3236 } else {
3237 // There are exactly two pointers.
3238 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3239 uint32_t id1 = idBits.clearFirstMarkedBit();
3240 uint32_t id2 = idBits.firstMarkedBit();
3241 const RawPointerData::Pointer& p1 =
3242 mCurrentRawState.rawPointerData.pointerForId(id1);
3243 const RawPointerData::Pointer& p2 =
3244 mCurrentRawState.rawPointerData.pointerForId(id2);
3245 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3246 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3247 // There are two pointers but they are too far apart for a SWIPE,
3248 // switch to FREEFORM.
3249 ALOGD_IF(DEBUG_GESTURES,
3250 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3251 mutualDistance, mPointerGestureMaxSwipeWidth);
3252 *cancelPreviousGesture = true;
3253 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3254 } else {
3255 // There are two pointers. Wait for both pointers to start moving
3256 // before deciding whether this is a SWIPE or FREEFORM gesture.
3257 float dist1 = dist[id1];
3258 float dist2 = dist[id2];
3259 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3260 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3261 // Calculate the dot product of the displacement vectors.
3262 // When the vectors are oriented in approximately the same direction,
3263 // the angle betweeen them is near zero and the cosine of the angle
3264 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3265 // mag(v2).
3266 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3267 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3268 float dx1 = delta1.dx * mPointerXZoomScale;
3269 float dy1 = delta1.dy * mPointerYZoomScale;
3270 float dx2 = delta2.dx * mPointerXZoomScale;
3271 float dy2 = delta2.dy * mPointerYZoomScale;
3272 float dot = dx1 * dx2 + dy1 * dy2;
3273 float cosine = dot / (dist1 * dist2); // denominator always > 0
3274 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3275 // Pointers are moving in the same direction. Switch to SWIPE.
3276 ALOGD_IF(DEBUG_GESTURES,
3277 "Gestures: PRESS transitioned to SWIPE, "
3278 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3279 "cosine %0.3f >= %0.3f",
3280 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3281 mConfig.pointerGestureMultitouchMinDistance, cosine,
3282 mConfig.pointerGestureSwipeTransitionAngleCosine);
3283 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3284 } else {
3285 // Pointers are moving in different directions. Switch to FREEFORM.
3286 ALOGD_IF(DEBUG_GESTURES,
3287 "Gestures: PRESS transitioned to FREEFORM, "
3288 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3289 "cosine %0.3f < %0.3f",
3290 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3291 mConfig.pointerGestureMultitouchMinDistance, cosine,
3292 mConfig.pointerGestureSwipeTransitionAngleCosine);
3293 *cancelPreviousGesture = true;
3294 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3295 }
3296 }
3297 }
3298 }
3299 }
3300 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3301 // Switch from SWIPE to FREEFORM if additional pointers go down.
3302 // Cancel previous gesture.
3303 if (currentFingerCount > 2) {
3304 ALOGD_IF(DEBUG_GESTURES,
3305 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3306 currentFingerCount);
3307 *cancelPreviousGesture = true;
3308 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3309 }
3310 }
3311
3312 // Move the reference points based on the overall group motion of the fingers
3313 // except in PRESS mode while waiting for a transition to occur.
3314 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3315 (commonDeltaRawX || commonDeltaRawY)) {
3316 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3317 uint32_t id = idBits.clearFirstMarkedBit();
3318 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3319 delta.dx = 0;
3320 delta.dy = 0;
3321 }
3322
3323 mPointerGesture.referenceTouchX += commonDeltaRawX;
3324 mPointerGesture.referenceTouchY += commonDeltaRawY;
3325
3326 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3327 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3328
3329 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3330 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3331
3332 mPointerGesture.referenceGestureX += commonDeltaX;
3333 mPointerGesture.referenceGestureY += commonDeltaY;
3334 }
3335
3336 // Report gestures.
3337 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3338 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3339 // PRESS or SWIPE mode.
3340 ALOGD_IF(DEBUG_GESTURES,
3341 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3342 "currentTouchPointerCount=%d",
3343 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3344 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3345
3346 mPointerGesture.currentGestureIdBits.clear();
3347 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3348 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3349 mPointerGesture.currentGestureProperties[0].clear();
3350 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3351 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3352 mPointerGesture.currentGestureCoords[0].clear();
3353 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3354 mPointerGesture.referenceGestureX);
3355 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3356 mPointerGesture.referenceGestureY);
3357 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3358 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3359 float xOffset = static_cast<float>(commonDeltaRawX) /
3360 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3361 float yOffset = static_cast<float>(commonDeltaRawY) /
3362 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3363 mPointerGesture.currentGestureCoords[0]
3364 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3365 mPointerGesture.currentGestureCoords[0]
3366 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3367 }
3368 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3369 // FREEFORM mode.
3370 ALOGD_IF(DEBUG_GESTURES,
3371 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3372 "currentTouchPointerCount=%d",
3373 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3374 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3375
3376 mPointerGesture.currentGestureIdBits.clear();
3377
3378 BitSet32 mappedTouchIdBits;
3379 BitSet32 usedGestureIdBits;
3380 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3381 // Initially, assign the active gesture id to the active touch point
3382 // if there is one. No other touch id bits are mapped yet.
3383 if (!*cancelPreviousGesture) {
3384 mappedTouchIdBits.markBit(activeTouchId);
3385 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3386 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3387 mPointerGesture.activeGestureId;
3388 } else {
3389 mPointerGesture.activeGestureId = -1;
3390 }
3391 } else {
3392 // Otherwise, assume we mapped all touches from the previous frame.
3393 // Reuse all mappings that are still applicable.
3394 mappedTouchIdBits.value =
3395 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3396 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3397
3398 // Check whether we need to choose a new active gesture id because the
3399 // current went went up.
3400 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3401 ~mCurrentCookedState.fingerIdBits.value);
3402 !upTouchIdBits.isEmpty();) {
3403 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3404 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3405 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3406 mPointerGesture.activeGestureId = -1;
3407 break;
3408 }
3409 }
3410 }
3411
3412 ALOGD_IF(DEBUG_GESTURES,
3413 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3414 "activeGestureId=%d",
3415 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3416
3417 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3418 for (uint32_t i = 0; i < currentFingerCount; i++) {
3419 uint32_t touchId = idBits.clearFirstMarkedBit();
3420 uint32_t gestureId;
3421 if (!mappedTouchIdBits.hasBit(touchId)) {
3422 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3423 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3424 ALOGD_IF(DEBUG_GESTURES,
3425 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3426 gestureId);
3427 } else {
3428 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3429 ALOGD_IF(DEBUG_GESTURES,
3430 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3431 touchId, gestureId);
3432 }
3433 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3434 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3435
3436 const RawPointerData::Pointer& pointer =
3437 mCurrentRawState.rawPointerData.pointerForId(touchId);
3438 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3439 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3440 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3441
3442 mPointerGesture.currentGestureProperties[i].clear();
3443 mPointerGesture.currentGestureProperties[i].id = gestureId;
3444 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3445 mPointerGesture.currentGestureCoords[i].clear();
3446 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3447 mPointerGesture.referenceGestureX +
3448 deltaX);
3449 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3450 mPointerGesture.referenceGestureY +
3451 deltaY);
3452 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3453 }
3454
3455 if (mPointerGesture.activeGestureId < 0) {
3456 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3457 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3458 mPointerGesture.activeGestureId);
3459 }
3460 }
3461}
3462
Harry Cutts714d1ad2022-08-24 16:36:43 +00003463void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3464 const RawPointerData::Pointer& currentPointer =
3465 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3466 const RawPointerData::Pointer& lastPointer =
3467 mLastRawState.rawPointerData.pointerForId(pointerId);
3468 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3469 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3470
3471 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3472 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3473
3474 mPointerController->move(deltaX, deltaY);
3475}
3476
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003477std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3478 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003479 mPointerSimple.currentCoords.clear();
3480 mPointerSimple.currentProperties.clear();
3481
3482 bool down, hovering;
3483 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3484 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3485 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003486 mPointerController
3487 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3488 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003489
3490 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3491 down = !hovering;
3492
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003493 float x, y;
3494 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003495 mPointerSimple.currentCoords.copyFrom(
3496 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3497 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3498 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3499 mPointerSimple.currentProperties.id = 0;
3500 mPointerSimple.currentProperties.toolType =
3501 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3502 } else {
3503 down = false;
3504 hovering = false;
3505 }
3506
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003507 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003508}
3509
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003510std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3511 uint32_t policyFlags) {
3512 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003513}
3514
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003515std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3516 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003517 mPointerSimple.currentCoords.clear();
3518 mPointerSimple.currentProperties.clear();
3519
3520 bool down, hovering;
3521 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3522 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003523 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003524 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003525 } else {
3526 mPointerVelocityControl.reset();
3527 }
3528
3529 down = isPointerDown(mCurrentRawState.buttonState);
3530 hovering = !down;
3531
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003532 float x, y;
3533 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003534 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003535 mPointerSimple.currentCoords.copyFrom(
3536 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3537 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3538 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3539 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3540 hovering ? 0.0f : 1.0f);
3541 mPointerSimple.currentProperties.id = 0;
3542 mPointerSimple.currentProperties.toolType =
3543 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3544 } else {
3545 mPointerVelocityControl.reset();
3546
3547 down = false;
3548 hovering = false;
3549 }
3550
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003551 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003552}
3553
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003554std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3555 uint32_t policyFlags) {
3556 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003557
3558 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003559
3560 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003561}
3562
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003563std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3564 uint32_t policyFlags, bool down,
3565 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003566 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3567 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003568 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003569 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003570
3571 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003572 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003573 mPointerController->clearSpots();
3574 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003575 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003576 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003577 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003578 }
Garfield Tan9514d782020-11-10 16:37:23 -08003579 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003580
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003581 float xCursorPosition, yCursorPosition;
3582 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003583
3584 if (mPointerSimple.down && !down) {
3585 mPointerSimple.down = false;
3586
3587 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003588 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3589 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3590 0, metaState, mLastRawState.buttonState,
3591 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3592 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3593 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3594 yCursorPosition, mPointerSimple.downTime,
3595 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003596 }
3597
3598 if (mPointerSimple.hovering && !hovering) {
3599 mPointerSimple.hovering = false;
3600
3601 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003602 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3603 mSource, displayId, policyFlags,
3604 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3605 mLastRawState.buttonState, MotionClassification::NONE,
3606 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3607 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3608 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3609 yCursorPosition, mPointerSimple.downTime,
3610 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003611 }
3612
3613 if (down) {
3614 if (!mPointerSimple.down) {
3615 mPointerSimple.down = true;
3616 mPointerSimple.downTime = when;
3617
3618 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003619 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3620 mSource, displayId, policyFlags,
3621 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3622 mCurrentRawState.buttonState, MotionClassification::NONE,
3623 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3624 &mPointerSimple.currentProperties,
3625 &mPointerSimple.currentCoords, mOrientedXPrecision,
3626 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3627 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003628 }
3629
3630 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003631 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3632 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3633 0, 0, metaState, mCurrentRawState.buttonState,
3634 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3635 &mPointerSimple.currentProperties,
3636 &mPointerSimple.currentCoords, mOrientedXPrecision,
3637 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3638 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003639 }
3640
3641 if (hovering) {
3642 if (!mPointerSimple.hovering) {
3643 mPointerSimple.hovering = true;
3644
3645 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003646 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3647 mSource, displayId, policyFlags,
3648 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3649 mCurrentRawState.buttonState, MotionClassification::NONE,
3650 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3651 &mPointerSimple.currentProperties,
3652 &mPointerSimple.currentCoords, mOrientedXPrecision,
3653 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3654 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003655 }
3656
3657 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003658 out.push_back(
3659 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3660 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3661 metaState, mCurrentRawState.buttonState,
3662 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3663 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3664 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3665 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003666 }
3667
3668 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3669 float vscroll = mCurrentRawState.rawVScroll;
3670 float hscroll = mCurrentRawState.rawHScroll;
3671 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3672 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3673
3674 // Send scroll.
3675 PointerCoords pointerCoords;
3676 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3677 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3678 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3679
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003680 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3681 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3682 0, 0, metaState, mCurrentRawState.buttonState,
3683 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3684 &mPointerSimple.currentProperties, &pointerCoords,
3685 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3686 yCursorPosition, mPointerSimple.downTime,
3687 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003688 }
3689
3690 // Save state.
3691 if (down || hovering) {
3692 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3693 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003694 mPointerSimple.displayId = displayId;
3695 mPointerSimple.source = mSource;
3696 mPointerSimple.lastCursorX = xCursorPosition;
3697 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003698 } else {
3699 mPointerSimple.reset();
3700 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003701 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003702}
3703
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003704std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3705 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003706 std::list<NotifyArgs> out;
3707 if (mPointerSimple.down || mPointerSimple.hovering) {
3708 int32_t metaState = getContext()->getGlobalMetaState();
3709 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3710 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3711 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3712 metaState, mLastRawState.buttonState,
3713 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3714 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3715 mOrientedXPrecision, mOrientedYPrecision,
3716 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3717 mPointerSimple.downTime,
3718 /* videoFrames */ {}));
3719 if (mPointerController != nullptr) {
3720 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3721 }
3722 }
3723 mPointerSimple.reset();
3724 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003725}
3726
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003727NotifyMotionArgs TouchInputMapper::dispatchMotion(
3728 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3729 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003730 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3731 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003732 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003733 PointerCoords pointerCoords[MAX_POINTERS];
3734 PointerProperties pointerProperties[MAX_POINTERS];
3735 uint32_t pointerCount = 0;
3736 while (!idBits.isEmpty()) {
3737 uint32_t id = idBits.clearFirstMarkedBit();
3738 uint32_t index = idToIndex[id];
3739 pointerProperties[pointerCount].copyFrom(properties[index]);
3740 pointerCoords[pointerCount].copyFrom(coords[index]);
3741
3742 if (changedId >= 0 && id == uint32_t(changedId)) {
3743 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3744 }
3745
3746 pointerCount += 1;
3747 }
3748
3749 ALOG_ASSERT(pointerCount != 0);
3750
3751 if (changedId >= 0 && pointerCount == 1) {
3752 // Replace initial down and final up action.
3753 // We can compare the action without masking off the changed pointer index
3754 // because we know the index is 0.
3755 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3756 action = AMOTION_EVENT_ACTION_DOWN;
3757 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003758 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3759 action = AMOTION_EVENT_ACTION_CANCEL;
3760 } else {
3761 action = AMOTION_EVENT_ACTION_UP;
3762 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003763 } else {
3764 // Can't happen.
3765 ALOG_ASSERT(false);
3766 }
3767 }
3768 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3769 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003770 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003771 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003772 }
3773 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3774 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003775 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003776 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003777 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003778 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3779 policyFlags, action, actionButton, flags, metaState, buttonState,
3780 classification, edgeFlags, pointerCount, pointerProperties,
3781 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3782 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003783}
3784
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003785std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3786 std::list<NotifyArgs> out;
3787 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3788 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3789 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003790}
3791
Prabir Pradhan1728b212021-10-19 16:00:03 -07003792// Transform input device coordinates to display panel coordinates.
3793void TouchInputMapper::rotateAndScale(float& x, float& y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003794 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3795 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3796
arthurhunga36b28e2020-12-29 20:28:15 +08003797 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3798 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3799
Prabir Pradhan1728b212021-10-19 16:00:03 -07003800 // Rotate to display coordinate.
Arthur Hung4197f6b2020-03-16 15:39:59 +08003801 // 0 - no swap and reverse.
3802 // 90 - swap x/y and reverse y.
3803 // 180 - reverse x, y.
3804 // 270 - swap x/y and reverse x.
Prabir Pradhan1728b212021-10-19 16:00:03 -07003805 switch (mInputDeviceOrientation) {
Michael Wrighta9cf4192022-12-01 23:46:39 +00003806 case ui::ROTATION_0:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003807 x = xScaled;
3808 y = yScaled;
Arthur Hung4197f6b2020-03-16 15:39:59 +08003809 break;
Michael Wrighta9cf4192022-12-01 23:46:39 +00003810 case ui::ROTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003811 y = xScaledMax;
3812 x = yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003813 break;
Michael Wrighta9cf4192022-12-01 23:46:39 +00003814 case ui::ROTATION_180:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003815 x = xScaledMax;
3816 y = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003817 break;
Michael Wrighta9cf4192022-12-01 23:46:39 +00003818 case ui::ROTATION_270:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003819 y = xScaled;
3820 x = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003821 break;
3822 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003823 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003824 }
3825}
3826
Prabir Pradhan1728b212021-10-19 16:00:03 -07003827bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003828 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3829 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3830
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003831 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003832 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00003833 isPointInRect(mPhysicalFrameInDisplay, xScaled, yScaled);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003834}
3835
3836const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3837 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003838 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3839 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3840 "left=%d, top=%d, right=%d, bottom=%d",
3841 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3842 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003843
3844 if (virtualKey.isHit(x, y)) {
3845 return &virtualKey;
3846 }
3847 }
3848
3849 return nullptr;
3850}
3851
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003852void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3853 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3854 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003855
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003856 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003857
3858 if (currentPointerCount == 0) {
3859 // No pointers to assign.
3860 return;
3861 }
3862
3863 if (lastPointerCount == 0) {
3864 // All pointers are new.
3865 for (uint32_t i = 0; i < currentPointerCount; i++) {
3866 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003867 current.rawPointerData.pointers[i].id = id;
3868 current.rawPointerData.idToIndex[id] = i;
3869 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003870 }
3871 return;
3872 }
3873
3874 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003875 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003876 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003877 uint32_t id = last.rawPointerData.pointers[0].id;
3878 current.rawPointerData.pointers[0].id = id;
3879 current.rawPointerData.idToIndex[id] = 0;
3880 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003881 return;
3882 }
3883
3884 // General case.
3885 // We build a heap of squared euclidean distances between current and last pointers
3886 // associated with the current and last pointer indices. Then, we find the best
3887 // match (by distance) for each current pointer.
3888 // The pointers must have the same tool type but it is possible for them to
3889 // transition from hovering to touching or vice-versa while retaining the same id.
3890 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3891
3892 uint32_t heapSize = 0;
3893 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3894 currentPointerIndex++) {
3895 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3896 lastPointerIndex++) {
3897 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003898 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003899 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003900 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003901 if (currentPointer.toolType == lastPointer.toolType) {
3902 int64_t deltaX = currentPointer.x - lastPointer.x;
3903 int64_t deltaY = currentPointer.y - lastPointer.y;
3904
3905 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3906
3907 // Insert new element into the heap (sift up).
3908 heap[heapSize].currentPointerIndex = currentPointerIndex;
3909 heap[heapSize].lastPointerIndex = lastPointerIndex;
3910 heap[heapSize].distance = distance;
3911 heapSize += 1;
3912 }
3913 }
3914 }
3915
3916 // Heapify
3917 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3918 startIndex -= 1;
3919 for (uint32_t parentIndex = startIndex;;) {
3920 uint32_t childIndex = parentIndex * 2 + 1;
3921 if (childIndex >= heapSize) {
3922 break;
3923 }
3924
3925 if (childIndex + 1 < heapSize &&
3926 heap[childIndex + 1].distance < heap[childIndex].distance) {
3927 childIndex += 1;
3928 }
3929
3930 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3931 break;
3932 }
3933
3934 swap(heap[parentIndex], heap[childIndex]);
3935 parentIndex = childIndex;
3936 }
3937 }
3938
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003939 if (DEBUG_POINTER_ASSIGNMENT) {
3940 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3941 for (size_t i = 0; i < heapSize; i++) {
3942 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3943 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3944 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003945 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003946
3947 // Pull matches out by increasing order of distance.
3948 // To avoid reassigning pointers that have already been matched, the loop keeps track
3949 // of which last and current pointers have been matched using the matchedXXXBits variables.
3950 // It also tracks the used pointer id bits.
3951 BitSet32 matchedLastBits(0);
3952 BitSet32 matchedCurrentBits(0);
3953 BitSet32 usedIdBits(0);
3954 bool first = true;
3955 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3956 while (heapSize > 0) {
3957 if (first) {
3958 // The first time through the loop, we just consume the root element of
3959 // the heap (the one with smallest distance).
3960 first = false;
3961 } else {
3962 // Previous iterations consumed the root element of the heap.
3963 // Pop root element off of the heap (sift down).
3964 heap[0] = heap[heapSize];
3965 for (uint32_t parentIndex = 0;;) {
3966 uint32_t childIndex = parentIndex * 2 + 1;
3967 if (childIndex >= heapSize) {
3968 break;
3969 }
3970
3971 if (childIndex + 1 < heapSize &&
3972 heap[childIndex + 1].distance < heap[childIndex].distance) {
3973 childIndex += 1;
3974 }
3975
3976 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3977 break;
3978 }
3979
3980 swap(heap[parentIndex], heap[childIndex]);
3981 parentIndex = childIndex;
3982 }
3983
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003984 if (DEBUG_POINTER_ASSIGNMENT) {
3985 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3986 for (size_t j = 0; j < heapSize; j++) {
3987 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3988 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3989 heap[j].distance);
3990 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003991 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003992 }
3993
3994 heapSize -= 1;
3995
3996 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3997 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3998
3999 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
4000 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
4001
4002 matchedCurrentBits.markBit(currentPointerIndex);
4003 matchedLastBits.markBit(lastPointerIndex);
4004
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004005 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
4006 current.rawPointerData.pointers[currentPointerIndex].id = id;
4007 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4008 current.rawPointerData.markIdBit(id,
4009 current.rawPointerData.isHovering(
4010 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004011 usedIdBits.markBit(id);
4012
Harry Cutts45483602022-08-24 14:36:48 +00004013 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4014 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
4015 ", distance=%" PRIu64,
4016 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004017 break;
4018 }
4019 }
4020
4021 // Assign fresh ids to pointers that were not matched in the process.
4022 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
4023 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
4024 uint32_t id = usedIdBits.markFirstUnmarkedBit();
4025
Siarhei Vishniakou57479982021-03-03 01:32:21 +00004026 current.rawPointerData.pointers[currentPointerIndex].id = id;
4027 current.rawPointerData.idToIndex[id] = currentPointerIndex;
4028 current.rawPointerData.markIdBit(id,
4029 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004030
Harry Cutts45483602022-08-24 14:36:48 +00004031 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
4032 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
4033 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004034 }
4035}
4036
4037int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
4038 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4039 return AKEY_STATE_VIRTUAL;
4040 }
4041
4042 for (const VirtualKey& virtualKey : mVirtualKeys) {
4043 if (virtualKey.keyCode == keyCode) {
4044 return AKEY_STATE_UP;
4045 }
4046 }
4047
4048 return AKEY_STATE_UNKNOWN;
4049}
4050
4051int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4052 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4053 return AKEY_STATE_VIRTUAL;
4054 }
4055
4056 for (const VirtualKey& virtualKey : mVirtualKeys) {
4057 if (virtualKey.scanCode == scanCode) {
4058 return AKEY_STATE_UP;
4059 }
4060 }
4061
4062 return AKEY_STATE_UNKNOWN;
4063}
4064
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004065bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
4066 const std::vector<int32_t>& keyCodes,
4067 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004068 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07004069 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004070 if (virtualKey.keyCode == keyCodes[i]) {
4071 outFlags[i] = 1;
4072 }
4073 }
4074 }
4075
4076 return true;
4077}
4078
4079std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4080 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004081 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004082 return std::make_optional(mPointerController->getDisplayId());
4083 } else {
4084 return std::make_optional(mViewport.displayId);
4085 }
4086 }
4087 return std::nullopt;
4088}
4089
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004090} // namespace android