blob: 9a7af40456cb9c7213f05cc9e344721c6bac39dc [file] [log] [blame]
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Michael Wright227c5542020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wright227c5542020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
21#include "TouchInputMapper.h"
22
Dominik Laskowski75788452021-02-09 18:51:25 -080023#include <ftl/enum.h>
Prabir Pradhan8d9ba912022-11-11 22:26:33 +000024#include <input/PrintTools.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080025
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070026#include "CursorButtonAccumulator.h"
27#include "CursorScrollAccumulator.h"
28#include "TouchButtonAccumulator.h"
29#include "TouchCursorInputMapperCommon.h"
Michael Wrighta9cf4192022-12-01 23:46:39 +000030#include "ui/Rotation.h"
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070031
32namespace android {
33
34// --- Constants ---
35
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070036// Artificial latency on synthetic events created from stylus data without corresponding touch
37// data.
38static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
39
HQ Liue6983c72022-04-19 22:14:56 +000040// Minimum width between two pointers to determine a gesture as freeform gesture in mm
41static const float MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER = 30;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070042// --- Static Definitions ---
43
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +000044static const DisplayViewport kUninitializedViewport;
45
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000046static std::string toString(const Rect& rect) {
47 return base::StringPrintf("Rect{%d, %d, %d, %d}", rect.left, rect.top, rect.right, rect.bottom);
48}
49
50static std::string toString(const ui::Size& size) {
51 return base::StringPrintf("%dx%d", size.width, size.height);
52}
53
Prabir Pradhan675f25a2022-11-10 22:04:07 +000054static bool isPointInRect(const Rect& rect, vec2 p) {
55 return p.x >= rect.left && p.x < rect.right && p.y >= rect.top && p.y < rect.bottom;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +000056}
57
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070058template <typename T>
59inline static void swap(T& a, T& b) {
60 T temp = a;
61 a = b;
62 b = temp;
63}
64
65static float calculateCommonVector(float a, float b) {
66 if (a > 0 && b > 0) {
67 return a < b ? a : b;
68 } else if (a < 0 && b < 0) {
69 return a > b ? a : b;
70 } else {
71 return 0;
72 }
73}
74
75inline static float distance(float x1, float y1, float x2, float y2) {
76 return hypotf(x1 - x2, y1 - y2);
77}
78
79inline static int32_t signExtendNybble(int32_t value) {
80 return value >= 8 ? value - 16 : value;
81}
82
Prabir Pradhan675f25a2022-11-10 22:04:07 +000083static ui::Size getNaturalDisplaySize(const DisplayViewport& viewport) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000084 ui::Size rotatedDisplaySize{viewport.deviceWidth, viewport.deviceHeight};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +000085 if (viewport.orientation == ui::ROTATION_90 || viewport.orientation == ui::ROTATION_270) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +000086 std::swap(rotatedDisplaySize.width, rotatedDisplaySize.height);
87 }
Prabir Pradhan675f25a2022-11-10 22:04:07 +000088 return rotatedDisplaySize;
Prabir Pradhan2d613f42022-11-10 20:22:06 +000089}
90
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070091// --- RawPointerData ---
92
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070093void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
94 float x = 0, y = 0;
95 uint32_t count = touchingIdBits.count();
96 if (count) {
97 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
98 uint32_t id = idBits.clearFirstMarkedBit();
99 const Pointer& pointer = pointerForId(id);
100 x += pointer.x;
101 y += pointer.y;
102 }
103 x /= count;
104 y /= count;
105 }
106 *outX = x;
107 *outY = y;
108}
109
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700110// --- TouchInputMapper ---
111
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800112TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
113 : InputMapper(deviceContext),
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000114 mTouchButtonAccumulator(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700115 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100116 mDeviceMode(DeviceMode::DISABLED),
Michael Wrighta9cf4192022-12-01 23:46:39 +0000117 mInputDeviceOrientation(ui::ROTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700118
119TouchInputMapper::~TouchInputMapper() {}
120
Philip Junker4af3b3d2021-12-14 10:36:55 +0100121uint32_t TouchInputMapper::getSources() const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700122 return mSource;
123}
124
125void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
126 InputMapper::populateDeviceInfo(info);
127
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000128 if (mDeviceMode == DeviceMode::DISABLED) {
129 return;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700130 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000131
132 info->addMotionRange(mOrientedRanges.x);
133 info->addMotionRange(mOrientedRanges.y);
134 info->addMotionRange(mOrientedRanges.pressure);
135
136 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
137 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
138 //
139 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
140 // motion, i.e. the hardware dimensions, as the finger could move completely across the
141 // touchpad in one sample cycle.
142 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
143 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
144 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat, x.fuzz,
145 x.resolution);
146 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat, y.fuzz,
147 y.resolution);
148 }
149
150 if (mOrientedRanges.size) {
151 info->addMotionRange(*mOrientedRanges.size);
152 }
153
154 if (mOrientedRanges.touchMajor) {
155 info->addMotionRange(*mOrientedRanges.touchMajor);
156 info->addMotionRange(*mOrientedRanges.touchMinor);
157 }
158
159 if (mOrientedRanges.toolMajor) {
160 info->addMotionRange(*mOrientedRanges.toolMajor);
161 info->addMotionRange(*mOrientedRanges.toolMinor);
162 }
163
164 if (mOrientedRanges.orientation) {
165 info->addMotionRange(*mOrientedRanges.orientation);
166 }
167
168 if (mOrientedRanges.distance) {
169 info->addMotionRange(*mOrientedRanges.distance);
170 }
171
172 if (mOrientedRanges.tilt) {
173 info->addMotionRange(*mOrientedRanges.tilt);
174 }
175
176 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
177 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
178 }
179 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
180 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
181 }
Prabir Pradhanedb0ba72022-10-04 15:44:11 +0000182 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000183 info->setSupportsUsi(mParameters.supportsUsi);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700184}
185
186void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700187 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800188 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700189 dumpParameters(dump);
190 dumpVirtualKeys(dump);
191 dumpRawPointerAxes(dump);
192 dumpCalibration(dump);
193 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700194 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700195
196 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000197 mRawToDisplay.dump(dump, "RawToDisplay Transform:", INDENT4);
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000198 mRawRotation.dump(dump, "RawRotation Transform:", INDENT4);
199 dump += StringPrintf(INDENT4 "OrientedXPrecision: %0.3f\n", mOrientedXPrecision);
200 dump += StringPrintf(INDENT4 "OrientedYPrecision: %0.3f\n", mOrientedYPrecision);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700201 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
202 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
203 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
204 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
205 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
206 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
207 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
208 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
209 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
210 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
211
212 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
213 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
214 mLastRawState.rawPointerData.pointerCount);
215 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
216 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
217 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
218 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
219 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
220 "toolType=%d, isHovering=%s\n",
221 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
222 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
223 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
224 pointer.distance, pointer.toolType, toString(pointer.isHovering));
225 }
226
227 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
228 mLastCookedState.buttonState);
229 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
230 mLastCookedState.cookedPointerData.pointerCount);
231 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
232 const PointerProperties& pointerProperties =
233 mLastCookedState.cookedPointerData.pointerProperties[i];
234 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000235 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
236 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
237 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700238 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
239 "toolType=%d, isHovering=%s\n",
240 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000241 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
242 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700243 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
244 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
245 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
246 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
247 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
248 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
249 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
250 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
251 pointerProperties.toolType,
252 toString(mLastCookedState.cookedPointerData.isHovering(i)));
253 }
254
255 dump += INDENT3 "Stylus Fusion:\n";
256 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
257 toString(mExternalStylusConnected));
Prabir Pradhan8d9ba912022-11-11 22:26:33 +0000258 dump += StringPrintf(INDENT4 "Fused External Stylus Pointer ID: %s\n",
259 toString(mFusedStylusPointerId).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700260 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
261 mExternalStylusFusionTimeout);
Prabir Pradhan124ea442022-10-28 20:27:44 +0000262 dump += StringPrintf(INDENT4 " External Stylus Buttons Applied: 0x%08x",
263 mExternalStylusButtonsApplied);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700264 dump += INDENT3 "External Stylus State:\n";
265 dumpStylusState(dump, mExternalStylusState);
266
Michael Wright227c5542020-07-02 18:30:52 +0100267 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700268 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
269 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
270 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
271 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
272 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
273 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
274 }
275}
276
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700277std::list<NotifyArgs> TouchInputMapper::configure(nsecs_t when,
278 const InputReaderConfiguration* config,
279 uint32_t changes) {
280 std::list<NotifyArgs> out = InputMapper::configure(when, config, changes);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700281
282 mConfig = *config;
283
284 if (!changes) { // first time only
285 // Configure basic parameters.
286 configureParameters();
287
288 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800289 mCursorScrollAccumulator.configure(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +0000290 mTouchButtonAccumulator.configure();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700291
292 // Configure absolute axis information.
293 configureRawPointerAxes();
294
295 // Prepare input device calibration.
296 parseCalibration();
297 resolveCalibration();
298 }
299
300 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
301 // Update location calibration to reflect current settings
302 updateAffineTransformation();
303 }
304
305 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
306 // Update pointer speed.
307 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
308 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
309 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
310 }
311
312 bool resetNeeded = false;
313 if (!changes ||
314 (changes &
315 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800316 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700317 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
318 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
319 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700320 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700321 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700322 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700323 }
324
325 if (changes && resetNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700326 out += reset(when);
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000327
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700328 // Send reset, unless this is the first time the device has been configured,
329 // in which case the reader will call reset itself after all mappers are ready.
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +0000330 out.emplace_back(NotifyDeviceResetArgs(getContext()->getNextId(), when, getDeviceId()));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700331 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -0700332 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700333}
334
335void TouchInputMapper::resolveExternalStylusPresence() {
336 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800337 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700338 mExternalStylusConnected = !devices.empty();
339
340 if (!mExternalStylusConnected) {
341 resetExternalStylus();
342 }
343}
344
345void TouchInputMapper::configureParameters() {
346 // Use the pointer presentation mode for devices that do not support distinct
347 // multitouch. The spot-based presentation relies on being able to accurately
348 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800349 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100350 ? Parameters::GestureMode::SINGLE_TOUCH
351 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700352
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700353 std::string gestureModeString;
354 if (getDeviceContext().getConfiguration().tryGetProperty("touch.gestureMode",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800355 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700356 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100357 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700358 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100359 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700360 } else if (gestureModeString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700361 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700362 }
363 }
364
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000365 configureDeviceType();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700366
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800367 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700368
Michael Wright227c5542020-07-02 18:30:52 +0100369 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700370 getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800371 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700372
Michael Wrighta9cf4192022-12-01 23:46:39 +0000373 mParameters.orientation = ui::ROTATION_0;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700374 std::string orientationString;
375 if (getDeviceContext().getConfiguration().tryGetProperty("touch.orientation",
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700376 orientationString)) {
377 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
378 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
379 } else if (orientationString == "ORIENTATION_90") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000380 mParameters.orientation = ui::ROTATION_90;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700381 } else if (orientationString == "ORIENTATION_180") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000382 mParameters.orientation = ui::ROTATION_180;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700383 } else if (orientationString == "ORIENTATION_270") {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000384 mParameters.orientation = ui::ROTATION_270;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700385 } else if (orientationString != "ORIENTATION_0") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700386 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.c_str());
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700387 }
388 }
389
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700390 mParameters.hasAssociatedDisplay = false;
391 mParameters.associatedDisplayIsExternal = false;
392 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100393 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000394 mParameters.deviceType == Parameters::DeviceType::POINTER ||
395 (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
396 getDeviceContext().getAssociatedViewport())) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700397 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100398 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800399 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700400 std::string uniqueDisplayId;
401 getDeviceContext().getConfiguration().tryGetProperty("touch.displayId",
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800402 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700403 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
404 }
405 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800406 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700407 mParameters.hasAssociatedDisplay = true;
408 }
409
410 // Initial downs on external touch devices should wake the device.
411 // Normally we don't do this for internal touch screens to prevent them from waking
412 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800413 mParameters.wake = getDeviceContext().isExternal();
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -0700414 getDeviceContext().getConfiguration().tryGetProperty("touch.wake", mParameters.wake);
Prabir Pradhan167c2702022-09-14 00:37:24 +0000415
416 mParameters.supportsUsi = false;
417 getDeviceContext().getConfiguration().tryGetProperty("touch.supportsUsi",
418 mParameters.supportsUsi);
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700419
420 mParameters.enableForInactiveViewport = false;
421 getDeviceContext().getConfiguration().tryGetProperty("touch.enableForInactiveViewport",
422 mParameters.enableForInactiveViewport);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700423}
424
Ambrus Weisz7bc23bf2022-10-04 13:13:07 +0000425void TouchInputMapper::configureDeviceType() {
426 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
427 // The device is a touch screen.
428 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
429 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
430 // The device is a pointing device like a track pad.
431 mParameters.deviceType = Parameters::DeviceType::POINTER;
432 } else {
433 // The device is a touch pad of unknown purpose.
434 mParameters.deviceType = Parameters::DeviceType::POINTER;
435 }
436
437 // Type association takes precedence over the device type found in the idc file.
438 std::string deviceTypeString = getDeviceContext().getDeviceTypeAssociation().value_or("");
439 if (deviceTypeString.empty()) {
440 getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType", deviceTypeString);
441 }
442 if (deviceTypeString == "touchScreen") {
443 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
444 } else if (deviceTypeString == "touchNavigation") {
445 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
446 } else if (deviceTypeString == "pointer") {
447 mParameters.deviceType = Parameters::DeviceType::POINTER;
448 } else if (deviceTypeString != "default" && deviceTypeString != "") {
449 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
450 }
451}
452
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700453void TouchInputMapper::dumpParameters(std::string& dump) {
454 dump += INDENT3 "Parameters:\n";
455
Dominik Laskowski75788452021-02-09 18:51:25 -0800456 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700457
Dominik Laskowski75788452021-02-09 18:51:25 -0800458 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700459
460 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
461 "displayId='%s'\n",
462 toString(mParameters.hasAssociatedDisplay),
463 toString(mParameters.associatedDisplayIsExternal),
464 mParameters.uniqueDisplayId.c_str());
465 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800466 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhan167c2702022-09-14 00:37:24 +0000467 dump += StringPrintf(INDENT4 "SupportsUsi: %s\n", toString(mParameters.supportsUsi));
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700468 dump += StringPrintf(INDENT4 "EnableForInactiveViewport: %s\n",
469 toString(mParameters.enableForInactiveViewport));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700470}
471
472void TouchInputMapper::configureRawPointerAxes() {
473 mRawPointerAxes.clear();
474}
475
476void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
477 dump += INDENT3 "Raw Touch Axes:\n";
478 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
479 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
480 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
481 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
482 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
483 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
484 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
485 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
486 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
487 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
488 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
489 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
490 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
491}
492
493bool TouchInputMapper::hasExternalStylus() const {
494 return mExternalStylusConnected;
495}
496
497/**
498 * Determine which DisplayViewport to use.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000499 * 1. If a device has associated display, get the matching viewport.
Garfield Tan888a6a42020-01-09 11:39:16 -0800500 * 2. Always use the suggested viewport from WindowManagerService for pointers.
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000501 * 3. Get the matching viewport by either unique id in idc file or by the display type
502 * (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800503 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700504 */
505std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800506 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Arthur Hung6d5b4b22022-01-21 07:21:10 +0000507 if (getDeviceContext().getAssociatedViewport()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800508 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700509 }
510
Christine Franks2a2293c2022-01-18 11:51:16 -0800511 const std::optional<std::string> associatedDisplayUniqueId =
512 getDeviceContext().getAssociatedDisplayUniqueId();
513 if (associatedDisplayUniqueId) {
514 return getDeviceContext().getAssociatedViewport();
515 }
516
Michael Wright227c5542020-07-02 18:30:52 +0100517 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800518 std::optional<DisplayViewport> viewport =
519 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
520 if (viewport) {
521 return viewport;
522 } else {
523 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
524 mConfig.defaultPointerDisplayId);
525 }
526 }
527
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700528 // Check if uniqueDisplayId is specified in idc file.
529 if (!mParameters.uniqueDisplayId.empty()) {
530 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
531 }
532
533 ViewportType viewportTypeToUse;
534 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100535 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700536 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100537 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700538 }
539
540 std::optional<DisplayViewport> viewport =
541 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100542 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700543 ALOGW("Input device %s should be associated with external display, "
544 "fallback to internal one for the external viewport is not found.",
545 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100546 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700547 }
548
549 return viewport;
550 }
551
552 // No associated display, return a non-display viewport.
553 DisplayViewport newViewport;
554 // Raw width and height in the natural orientation.
555 int32_t rawWidth = mRawPointerAxes.getRawWidth();
556 int32_t rawHeight = mRawPointerAxes.getRawHeight();
557 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
558 return std::make_optional(newViewport);
559}
560
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800561int32_t TouchInputMapper::clampResolution(const char* axisName, int32_t resolution) const {
562 if (resolution < 0) {
563 ALOGE("Invalid %s resolution %" PRId32 " for device %s", axisName, resolution,
564 getDeviceName().c_str());
565 return 0;
566 }
567 return resolution;
568}
569
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800570void TouchInputMapper::initializeSizeRanges() {
571 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::NONE) {
572 mSizeScale = 0.0f;
573 return;
574 }
575
576 // Size of diagonal axis.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000577 const float diagonalSize = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800578
579 // Size factors.
580 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
581 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
582 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
583 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
584 } else {
585 mSizeScale = 0.0f;
586 }
587
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700588 mOrientedRanges.touchMajor = InputDeviceInfo::MotionRange{
589 .axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR,
590 .source = mSource,
591 .min = 0,
592 .max = diagonalSize,
593 .flat = 0,
594 .fuzz = 0,
595 .resolution = 0,
596 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800597
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800598 if (mRawPointerAxes.touchMajor.valid) {
599 mRawPointerAxes.touchMajor.resolution =
600 clampResolution("touchMajor", mRawPointerAxes.touchMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700601 mOrientedRanges.touchMajor->resolution = mRawPointerAxes.touchMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800602 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800603
604 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700605 mOrientedRanges.touchMinor->axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800606 if (mRawPointerAxes.touchMinor.valid) {
607 mRawPointerAxes.touchMinor.resolution =
608 clampResolution("touchMinor", mRawPointerAxes.touchMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700609 mOrientedRanges.touchMinor->resolution = mRawPointerAxes.touchMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800610 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800611
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700612 mOrientedRanges.toolMajor = InputDeviceInfo::MotionRange{
613 .axis = AMOTION_EVENT_AXIS_TOOL_MAJOR,
614 .source = mSource,
615 .min = 0,
616 .max = diagonalSize,
617 .flat = 0,
618 .fuzz = 0,
619 .resolution = 0,
620 };
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800621 if (mRawPointerAxes.toolMajor.valid) {
622 mRawPointerAxes.toolMajor.resolution =
623 clampResolution("toolMajor", mRawPointerAxes.toolMajor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700624 mOrientedRanges.toolMajor->resolution = mRawPointerAxes.toolMajor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800625 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800626
627 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700628 mOrientedRanges.toolMinor->axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800629 if (mRawPointerAxes.toolMinor.valid) {
630 mRawPointerAxes.toolMinor.resolution =
631 clampResolution("toolMinor", mRawPointerAxes.toolMinor.resolution);
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700632 mOrientedRanges.toolMinor->resolution = mRawPointerAxes.toolMinor.resolution;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800633 }
634
635 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700636 mOrientedRanges.touchMajor->resolution *= mGeometricScale;
637 mOrientedRanges.touchMinor->resolution *= mGeometricScale;
638 mOrientedRanges.toolMajor->resolution *= mGeometricScale;
639 mOrientedRanges.toolMinor->resolution *= mGeometricScale;
Siarhei Vishniakou12c0fcb2021-12-17 13:40:44 -0800640 } else {
641 // Support for other calibrations can be added here.
642 ALOGW("%s calibration is not supported for size ranges at the moment. "
643 "Using raw resolution instead",
644 ftl::enum_string(mCalibration.sizeCalibration).c_str());
645 }
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800646
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700647 mOrientedRanges.size = InputDeviceInfo::MotionRange{
648 .axis = AMOTION_EVENT_AXIS_SIZE,
649 .source = mSource,
650 .min = 0,
651 .max = 1.0,
652 .flat = 0,
653 .fuzz = 0,
654 .resolution = 0,
655 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800656}
657
658void TouchInputMapper::initializeOrientedRanges() {
659 // Configure X and Y factors.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000660 const float orientedScaleX = mRawToDisplay.getScaleX();
661 const float orientedScaleY = mRawToDisplay.getScaleY();
662 mOrientedXPrecision = 1.0f / orientedScaleX;
663 mOrientedYPrecision = 1.0f / orientedScaleY;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800664
665 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
666 mOrientedRanges.x.source = mSource;
667 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
668 mOrientedRanges.y.source = mSource;
669
670 // Scale factor for terms that are not oriented in a particular axis.
671 // If the pixels are square then xScale == yScale otherwise we fake it
672 // by choosing an average.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000673 mGeometricScale = avg(orientedScaleX, orientedScaleY);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800674
675 initializeSizeRanges();
676
677 // Pressure factors.
678 mPressureScale = 0;
679 float pressureMax = 1.0;
680 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
681 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700682 if (mCalibration.pressureScale) {
683 mPressureScale = *mCalibration.pressureScale;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800684 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
685 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
686 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
687 }
688 }
689
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700690 mOrientedRanges.pressure = InputDeviceInfo::MotionRange{
691 .axis = AMOTION_EVENT_AXIS_PRESSURE,
692 .source = mSource,
693 .min = 0,
694 .max = pressureMax,
695 .flat = 0,
696 .fuzz = 0,
697 .resolution = 0,
698 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800699
700 // Tilt
701 mTiltXCenter = 0;
702 mTiltXScale = 0;
703 mTiltYCenter = 0;
704 mTiltYScale = 0;
705 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
706 if (mHaveTilt) {
707 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
708 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
709 mTiltXScale = M_PI / 180;
710 mTiltYScale = M_PI / 180;
711
712 if (mRawPointerAxes.tiltX.resolution) {
713 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
714 }
715 if (mRawPointerAxes.tiltY.resolution) {
716 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
717 }
718
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700719 mOrientedRanges.tilt = InputDeviceInfo::MotionRange{
720 .axis = AMOTION_EVENT_AXIS_TILT,
721 .source = mSource,
722 .min = 0,
723 .max = M_PI_2,
724 .flat = 0,
725 .fuzz = 0,
726 .resolution = 0,
727 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800728 }
729
730 // Orientation
731 mOrientationScale = 0;
732 if (mHaveTilt) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700733 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
734 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
735 .source = mSource,
736 .min = -M_PI,
737 .max = M_PI,
738 .flat = 0,
739 .fuzz = 0,
740 .resolution = 0,
741 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800742
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800743 } else if (mCalibration.orientationCalibration != Calibration::OrientationCalibration::NONE) {
744 if (mCalibration.orientationCalibration ==
745 Calibration::OrientationCalibration::INTERPOLATED) {
746 if (mRawPointerAxes.orientation.valid) {
747 if (mRawPointerAxes.orientation.maxValue > 0) {
748 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
749 } else if (mRawPointerAxes.orientation.minValue < 0) {
750 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
751 } else {
752 mOrientationScale = 0;
753 }
754 }
755 }
756
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700757 mOrientedRanges.orientation = InputDeviceInfo::MotionRange{
758 .axis = AMOTION_EVENT_AXIS_ORIENTATION,
759 .source = mSource,
760 .min = -M_PI_2,
761 .max = M_PI_2,
762 .flat = 0,
763 .fuzz = 0,
764 .resolution = 0,
765 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800766 }
767
768 // Distance
769 mDistanceScale = 0;
770 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
771 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700772 mDistanceScale = mCalibration.distanceScale.value_or(1.0f);
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800773 }
774
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700775 mOrientedRanges.distance = InputDeviceInfo::MotionRange{
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800776
Siarhei Vishniakou24210882022-07-15 09:42:04 -0700777 .axis = AMOTION_EVENT_AXIS_DISTANCE,
778 .source = mSource,
779 .min = mRawPointerAxes.distance.minValue * mDistanceScale,
780 .max = mRawPointerAxes.distance.maxValue * mDistanceScale,
781 .flat = 0,
782 .fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale,
783 .resolution = 0,
784 };
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800785 }
786
787 // Compute oriented precision, scales and ranges.
788 // Note that the maximum value reported is an inclusive maximum value so it is one
789 // unit less than the total width or height of the display.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000790 // TODO(b/20508709): Calculate the oriented ranges using the input device's raw frame.
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800791 switch (mInputDeviceOrientation) {
Michael Wrighta9cf4192022-12-01 23:46:39 +0000792 case ui::ROTATION_90:
793 case ui::ROTATION_270:
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800794 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000795 mOrientedRanges.x.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800796 mOrientedRanges.x.flat = 0;
797 mOrientedRanges.x.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000798 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mRawToDisplay.getScaleY();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800799
800 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000801 mOrientedRanges.y.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800802 mOrientedRanges.y.flat = 0;
803 mOrientedRanges.y.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000804 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mRawToDisplay.getScaleX();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800805 break;
806
807 default:
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800808 mOrientedRanges.x.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000809 mOrientedRanges.x.max = mDisplayBounds.width - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800810 mOrientedRanges.x.flat = 0;
811 mOrientedRanges.x.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000812 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mRawToDisplay.getScaleX();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800813
814 mOrientedRanges.y.min = 0;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000815 mOrientedRanges.y.max = mDisplayBounds.height - 1;
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800816 mOrientedRanges.y.flat = 0;
817 mOrientedRanges.y.fuzz = 0;
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000818 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mRawToDisplay.getScaleY();
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800819 break;
820 }
821}
822
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000823void TouchInputMapper::computeInputTransforms() {
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000824 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
825
826 ui::Size rotatedRawSize = rawSize;
827 if (mInputDeviceOrientation == ui::ROTATION_270 || mInputDeviceOrientation == ui::ROTATION_90) {
828 std::swap(rotatedRawSize.width, rotatedRawSize.height);
829 }
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000830 const auto rotationFlags = ui::Transform::toRotationFlags(-mInputDeviceOrientation);
831 mRawRotation = ui::Transform{rotationFlags};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000832
833 // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
834 ui::Transform undoRawOffset;
835 undoRawOffset.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
836
837 // Step 2: Rotate the raw coordinates to the expected orientation.
838 ui::Transform rotate;
839 // When rotating raw coordinates, the raw size will be used as an offset.
840 // Account for the extra unit added to the raw range when the raw size was calculated.
Prabir Pradhane2e10b42022-11-17 20:59:36 +0000841 rotate.set(rotationFlags, rotatedRawSize.width - 1, rotatedRawSize.height - 1);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000842
843 // Step 3: Scale the raw coordinates to the display space.
844 ui::Transform scaleToDisplay;
845 const float xScale = static_cast<float>(mDisplayBounds.width) / rotatedRawSize.width;
846 const float yScale = static_cast<float>(mDisplayBounds.height) / rotatedRawSize.height;
847 scaleToDisplay.set(xScale, 0, 0, yScale);
848
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000849 mRawToDisplay = (scaleToDisplay * (rotate * undoRawOffset));
850
851 // Calculate the transform that takes raw coordinates to the rotated display space.
852 ui::Transform displayToRotatedDisplay;
853 displayToRotatedDisplay.set(ui::Transform::toRotationFlags(-mViewport.orientation),
854 mViewport.deviceWidth, mViewport.deviceHeight);
855 mRawToRotatedDisplay = displayToRotatedDisplay * mRawToDisplay;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000856}
857
Prabir Pradhan1728b212021-10-19 16:00:03 -0700858void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000859 const DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700860
861 resolveExternalStylusPresence();
862
863 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100864 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000865 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700866 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100867 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700868 if (hasStylus()) {
869 mSource |= AINPUT_SOURCE_STYLUS;
Harry Cutts16a24cc2022-10-26 15:22:19 +0000870 } else {
871 mSource |= AINPUT_SOURCE_TOUCHPAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700872 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800873 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700874 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100875 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700876 if (hasStylus()) {
877 mSource |= AINPUT_SOURCE_STYLUS;
878 }
879 if (hasExternalStylus()) {
880 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
881 }
Michael Wright227c5542020-07-02 18:30:52 +0100882 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700883 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100884 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700885 } else {
886 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100887 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700888 }
889
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000890 const std::optional<DisplayViewport> newViewportOpt = findViewport();
891
892 // Ensure the device is valid and can be used.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700893 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
894 ALOGW("Touch device '%s' did not report support for X or Y axis! "
895 "The device will be inoperable.",
896 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100897 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000898 } else if (!newViewportOpt) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700899 ALOGI("Touch device '%s' could not query the properties of its associated "
900 "display. The device will be inoperable until the display size "
901 "becomes available.",
902 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100903 mDeviceMode = DeviceMode::DISABLED;
Yuncheol Heo50c19b12022-11-02 20:33:08 -0700904 } else if (!mParameters.enableForInactiveViewport && !newViewportOpt->isActive) {
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000905 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
906 getDeviceName().c_str(), getDeviceId());
907 mDeviceMode = DeviceMode::DISABLED;
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000908 }
909
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700910 // Raw width and height in the natural orientation.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000911 const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
HQ Liue6983c72022-04-19 22:14:56 +0000912 const int32_t rawXResolution = mRawPointerAxes.x.resolution;
913 const int32_t rawYResolution = mRawPointerAxes.y.resolution;
914 // Calculate the mean resolution when both x and y resolution are set, otherwise set it to 0.
915 const float rawMeanResolution =
916 (rawXResolution > 0 && rawYResolution > 0) ? (rawXResolution + rawYResolution) / 2 : 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700917
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000918 const DisplayViewport& newViewport = newViewportOpt.value_or(kUninitializedViewport);
919 const bool viewportChanged = mViewport != newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700920 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700921 if (viewportChanged) {
Prabir Pradhanc0bdeef2022-08-05 22:32:11 +0000922 const bool viewportOrientationChanged = mViewport.orientation != newViewport.orientation;
923 const bool viewportDisplayIdChanged = mViewport.displayId != newViewport.displayId;
924 mViewport = newViewport;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700925
Michael Wright227c5542020-07-02 18:30:52 +0100926 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan2d613f42022-11-10 20:22:06 +0000927 const auto oldDisplayBounds = mDisplayBounds;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700928
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000929 mDisplayBounds = getNaturalDisplaySize(mViewport);
930 mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
931 mViewport.physicalRight, mViewport.physicalBottom};
Prabir Pradhan5632d622021-09-06 07:57:20 -0700932
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000933 // InputReader works in the un-rotated display coordinate space, so we don't need to do
934 // anything if the device is already orientation-aware. If the device is not
935 // orientation-aware, then we need to apply the inverse rotation of the display so that
936 // when the display rotation is applied later as a part of the per-window transform, we
937 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700938 mInputDeviceOrientation = mParameters.orientationAware
Michael Wrighta9cf4192022-12-01 23:46:39 +0000939 ? ui::ROTATION_0
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000940 : getInverseRotation(mViewport.orientation);
941 // For orientation-aware devices that work in the un-rotated coordinate space, the
942 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan3e5ec702022-07-29 16:26:24 +0000943 skipViewportUpdate = !viewportDisplayIdChanged && mParameters.orientationAware &&
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000944 mDisplayBounds == oldDisplayBounds && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700945
946 // Apply the input device orientation for the device.
Michael Wrighta9cf4192022-12-01 23:46:39 +0000947 mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000948 computeInputTransforms();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700949 } else {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000950 mDisplayBounds = rawSize;
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000951 mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
Michael Wrighta9cf4192022-12-01 23:46:39 +0000952 mInputDeviceOrientation = ui::ROTATION_0;
Prabir Pradhanea31d4f2022-11-10 20:48:01 +0000953 mRawToDisplay.reset();
954 mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
Prabir Pradhan675f25a2022-11-10 22:04:07 +0000955 mRawToRotatedDisplay = mRawToDisplay;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700956 }
957 }
958
959 // If moving between pointer modes, need to reset some state.
960 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
961 if (deviceModeChanged) {
962 mOrientedRanges.clear();
963 }
964
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800965 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
966 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100967 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800968 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000969 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
970 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800971 if (mPointerController == nullptr) {
972 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700973 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000974 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800975 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
976 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700977 } else {
lilinnandef700b2022-06-17 19:32:01 +0800978 if (mPointerController != nullptr && mDeviceMode == DeviceMode::DIRECT &&
979 !mConfig.showTouches) {
980 mPointerController->clearSpots();
981 }
Michael Wright17db18e2020-06-26 20:51:44 +0100982 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700983 }
984
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700985 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000986 ALOGI("Device reconfigured: id=%d, name='%s', size %s, orientation %d, mode %d, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700987 "display id %d",
Prabir Pradhan7ddbc952022-11-09 22:03:40 +0000988 getDeviceId(), getDeviceName().c_str(), toString(mDisplayBounds).c_str(),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700989 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700990
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700991 configureVirtualKeys();
992
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -0800993 initializeOrientedRanges();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700994
995 // Location
996 updateAffineTransformation();
997
Michael Wright227c5542020-07-02 18:30:52 +0100998 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700999 // Compute pointer gesture detection parameters.
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001000 float rawDiagonal = hypotf(rawSize.width, rawSize.height);
1001 float displayDiagonal = hypotf(mDisplayBounds.width, mDisplayBounds.height);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001002
1003 // Scale movements such that one whole swipe of the touch pad covers a
1004 // given area relative to the diagonal size of the display when no acceleration
1005 // is applied.
1006 // Assume that the touch pad has a square aspect ratio such that movements in
1007 // X and Y of the same number of raw units cover the same physical distance.
1008 mPointerXMovementScale =
1009 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1010 mPointerYMovementScale = mPointerXMovementScale;
1011
1012 // Scale zooms to cover a smaller range of the display than movements do.
1013 // This value determines the area around the pointer that is affected by freeform
1014 // pointer gestures.
1015 mPointerXZoomScale =
1016 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1017 mPointerYZoomScale = mPointerXZoomScale;
1018
HQ Liue6983c72022-04-19 22:14:56 +00001019 // Calculate the min freeform gesture width. It will be 0 when the resolution of any
1020 // axis is non positive value.
1021 const float minFreeformGestureWidth =
1022 rawMeanResolution * MIN_FREEFORM_GESTURE_WIDTH_IN_MILLIMETER;
1023
1024 mPointerGestureMaxSwipeWidth =
1025 std::max(mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal,
1026 minFreeformGestureWidth);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001027 }
1028
1029 // Inform the dispatcher about the changes.
1030 *outResetNeeded = true;
1031 bumpGeneration();
1032 }
1033}
1034
Prabir Pradhan1728b212021-10-19 16:00:03 -07001035void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001036 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001037 dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
Prabir Pradhan675f25a2022-11-10 22:04:07 +00001038 dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
1039 toString(mPhysicalFrameInRotatedDisplay).c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001040 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001041}
1042
1043void TouchInputMapper::configureVirtualKeys() {
1044 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001045 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001046
1047 mVirtualKeys.clear();
1048
1049 if (virtualKeyDefinitions.size() == 0) {
1050 return;
1051 }
1052
1053 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1054 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1055 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1056 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1057
1058 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1059 VirtualKey virtualKey;
1060
1061 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1062 int32_t keyCode;
1063 int32_t dummyKeyMetaState;
1064 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001065 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1066 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001067 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1068 continue; // drop the key
1069 }
1070
1071 virtualKey.keyCode = keyCode;
1072 virtualKey.flags = flags;
1073
1074 // convert the key definition's display coordinates into touch coordinates for a hit box
1075 int32_t halfWidth = virtualKeyDefinition.width / 2;
1076 int32_t halfHeight = virtualKeyDefinition.height / 2;
1077
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001078 virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth /
1079 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001080 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001081 virtualKey.hitRight = (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth /
1082 mDisplayBounds.width +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001083 touchScreenLeft;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001084 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1085 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001086 touchScreenTop;
Prabir Pradhan7ddbc952022-11-09 22:03:40 +00001087 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1088 mDisplayBounds.height +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001089 touchScreenTop;
1090 mVirtualKeys.push_back(virtualKey);
1091 }
1092}
1093
1094void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1095 if (!mVirtualKeys.empty()) {
1096 dump += INDENT3 "Virtual Keys:\n";
1097
1098 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1099 const VirtualKey& virtualKey = mVirtualKeys[i];
1100 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1101 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1102 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1103 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1104 }
1105 }
1106}
1107
1108void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001109 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001110 Calibration& out = mCalibration;
1111
1112 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001113 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001114 std::string sizeCalibrationString;
1115 if (in.tryGetProperty("touch.size.calibration", sizeCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001116 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001117 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001118 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001119 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001120 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001121 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001122 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001123 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001124 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001125 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001126 } else if (sizeCalibrationString != "default") {
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001127 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001128 }
1129 }
1130
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001131 float sizeScale;
1132
1133 if (in.tryGetProperty("touch.size.scale", sizeScale)) {
1134 out.sizeScale = sizeScale;
1135 }
1136 float sizeBias;
1137 if (in.tryGetProperty("touch.size.bias", sizeBias)) {
1138 out.sizeBias = sizeBias;
1139 }
1140 bool sizeIsSummed;
1141 if (in.tryGetProperty("touch.size.isSummed", sizeIsSummed)) {
1142 out.sizeIsSummed = sizeIsSummed;
1143 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001144
1145 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001146 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001147 std::string pressureCalibrationString;
1148 if (in.tryGetProperty("touch.pressure.calibration", pressureCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001149 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001150 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001151 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001152 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001153 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001154 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001155 } else if (pressureCalibrationString != "default") {
1156 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001157 pressureCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001158 }
1159 }
1160
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001161 float pressureScale;
1162 if (in.tryGetProperty("touch.pressure.scale", pressureScale)) {
1163 out.pressureScale = pressureScale;
1164 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001165
1166 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001167 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001168 std::string orientationCalibrationString;
1169 if (in.tryGetProperty("touch.orientation.calibration", orientationCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001171 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001172 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001173 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001175 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001176 } else if (orientationCalibrationString != "default") {
1177 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001178 orientationCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001179 }
1180 }
1181
1182 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001183 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001184 std::string distanceCalibrationString;
1185 if (in.tryGetProperty("touch.distance.calibration", distanceCalibrationString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001186 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001187 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001188 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001189 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001190 } else if (distanceCalibrationString != "default") {
1191 ALOGW("Invalid value for touch.distance.calibration: '%s'",
Siarhei Vishniakou4f94c1a2022-07-13 07:29:51 -07001192 distanceCalibrationString.c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001193 }
1194 }
1195
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001196 float distanceScale;
1197 if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
1198 out.distanceScale = distanceScale;
1199 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001200}
1201
1202void TouchInputMapper::resolveCalibration() {
1203 // Size
1204 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001205 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1206 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001207 }
1208 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001209 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001210 }
1211
1212 // Pressure
1213 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001214 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1215 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001216 }
1217 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001218 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001219 }
1220
1221 // Orientation
1222 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001223 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1224 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001225 }
1226 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001227 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001228 }
1229
1230 // Distance
1231 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001232 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1233 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001234 }
1235 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001236 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001237 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001238}
1239
1240void TouchInputMapper::dumpCalibration(std::string& dump) {
1241 dump += INDENT3 "Calibration:\n";
1242
Siarhei Vishniakou4e837cc2021-12-20 23:24:33 -08001243 dump += INDENT4 "touch.size.calibration: ";
1244 dump += ftl::enum_string(mCalibration.sizeCalibration) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001245
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001246 if (mCalibration.sizeScale) {
1247 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", *mCalibration.sizeScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001248 }
1249
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001250 if (mCalibration.sizeBias) {
1251 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", *mCalibration.sizeBias);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001252 }
1253
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001254 if (mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001255 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001256 toString(*mCalibration.sizeIsSummed));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001257 }
1258
1259 // Pressure
1260 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001261 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001262 dump += INDENT4 "touch.pressure.calibration: none\n";
1263 break;
Michael Wright227c5542020-07-02 18:30:52 +01001264 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001265 dump += INDENT4 "touch.pressure.calibration: physical\n";
1266 break;
Michael Wright227c5542020-07-02 18:30:52 +01001267 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001268 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1269 break;
1270 default:
1271 ALOG_ASSERT(false);
1272 }
1273
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001274 if (mCalibration.pressureScale) {
1275 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", *mCalibration.pressureScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001276 }
1277
1278 // Orientation
1279 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001280 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281 dump += INDENT4 "touch.orientation.calibration: none\n";
1282 break;
Michael Wright227c5542020-07-02 18:30:52 +01001283 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1285 break;
Michael Wright227c5542020-07-02 18:30:52 +01001286 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001287 dump += INDENT4 "touch.orientation.calibration: vector\n";
1288 break;
1289 default:
1290 ALOG_ASSERT(false);
1291 }
1292
1293 // Distance
1294 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001295 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001296 dump += INDENT4 "touch.distance.calibration: none\n";
1297 break;
Michael Wright227c5542020-07-02 18:30:52 +01001298 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001299 dump += INDENT4 "touch.distance.calibration: scaled\n";
1300 break;
1301 default:
1302 ALOG_ASSERT(false);
1303 }
1304
Siarhei Vishniakou24210882022-07-15 09:42:04 -07001305 if (mCalibration.distanceScale) {
1306 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001308}
1309
1310void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1311 dump += INDENT3 "Affine Transformation:\n";
1312
1313 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1314 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1315 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1316 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1317 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1318 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1319}
1320
1321void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001322 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001323 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001324}
1325
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001326std::list<NotifyArgs> TouchInputMapper::reset(nsecs_t when) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001327 std::list<NotifyArgs> out = cancelTouch(when, when);
1328 updateTouchSpots();
1329
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001330 mCursorButtonAccumulator.reset(getDeviceContext());
1331 mCursorScrollAccumulator.reset(getDeviceContext());
Prabir Pradhan4f05b5f2022-10-11 21:24:07 +00001332 mTouchButtonAccumulator.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001333
1334 mPointerVelocityControl.reset();
1335 mWheelXVelocityControl.reset();
1336 mWheelYVelocityControl.reset();
1337
1338 mRawStatesPending.clear();
1339 mCurrentRawState.clear();
1340 mCurrentCookedState.clear();
1341 mLastRawState.clear();
1342 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001343 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001344 mSentHoverEnter = false;
1345 mHavePointerIds = false;
1346 mCurrentMotionAborted = false;
1347 mDownTime = 0;
1348
1349 mCurrentVirtualKey.down = false;
1350
1351 mPointerGesture.reset();
1352 mPointerSimple.reset();
1353 resetExternalStylus();
1354
1355 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001356 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001357 mPointerController->clearSpots();
1358 }
1359
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001360 return out += InputMapper::reset(when);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001361}
1362
1363void TouchInputMapper::resetExternalStylus() {
1364 mExternalStylusState.clear();
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001365 mFusedStylusPointerId.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001366 mExternalStylusFusionTimeout = LLONG_MAX;
1367 mExternalStylusDataPending = false;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001368 mExternalStylusButtonsApplied = 0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001369}
1370
1371void TouchInputMapper::clearStylusDataPendingFlags() {
1372 mExternalStylusDataPending = false;
1373 mExternalStylusFusionTimeout = LLONG_MAX;
1374}
1375
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001376std::list<NotifyArgs> TouchInputMapper::process(const RawEvent* rawEvent) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001377 mCursorButtonAccumulator.process(rawEvent);
1378 mCursorScrollAccumulator.process(rawEvent);
1379 mTouchButtonAccumulator.process(rawEvent);
1380
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001381 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001382 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001383 out += sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001384 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001385 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001386}
1387
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001388std::list<NotifyArgs> TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
1389 std::list<NotifyArgs> out;
Prabir Pradhanafabcde2022-09-27 19:32:43 +00001390 if (mDeviceMode == DeviceMode::DISABLED) {
1391 // Only save the last pending state when the device is disabled.
1392 mRawStatesPending.clear();
1393 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001394 // Push a new state.
1395 mRawStatesPending.emplace_back();
1396
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001397 RawState& next = mRawStatesPending.back();
1398 next.clear();
1399 next.when = when;
1400 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001401
1402 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001403 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001404 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1405
1406 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001407 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1408 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001409 mCursorScrollAccumulator.finishSync();
1410
1411 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001412 syncTouch(when, &next);
1413
1414 // The last RawState is the actually second to last, since we just added a new state
1415 const RawState& last =
1416 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001417
Prabir Pradhan61a243a2022-11-16 23:47:36 +00001418 std::tie(next.when, next.readTime) =
1419 applyBluetoothTimestampSmoothening(getDeviceContext().getDeviceIdentifier(), when,
1420 readTime, last.when);
Prabir Pradhan2f37bcb2022-11-08 20:41:28 +00001421
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001422 // Assign pointer ids.
1423 if (!mHavePointerIds) {
1424 assignPointerIds(last, next);
1425 }
1426
Harry Cutts45483602022-08-24 14:36:48 +00001427 ALOGD_IF(DEBUG_RAW_EVENTS,
1428 "syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
1429 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
1430 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1431 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1432 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1433 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001434
Arthur Hung9ad18942021-06-19 02:04:46 +00001435 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1436 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1437 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1438 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1439 next.rawPointerData.hoveringIdBits.value);
1440 }
1441
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001442 out += processRawTouches(false /*timeout*/);
1443 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001444}
1445
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001446std::list<NotifyArgs> TouchInputMapper::processRawTouches(bool timeout) {
1447 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001448 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001449 // Do not process raw event while the device is disabled.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001450 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001451 }
1452
1453 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1454 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1455 // touching the current state will only observe the events that have been dispatched to the
1456 // rest of the pipeline.
1457 const size_t N = mRawStatesPending.size();
1458 size_t count;
1459 for (count = 0; count < N; count++) {
1460 const RawState& next = mRawStatesPending[count];
1461
1462 // A failure to assign the stylus id means that we're waiting on stylus data
1463 // and so should defer the rest of the pipeline.
1464 if (assignExternalStylusId(next, timeout)) {
1465 break;
1466 }
1467
1468 // All ready to go.
1469 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001470 mCurrentRawState = next;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001471 if (mCurrentRawState.when < mLastRawState.when) {
1472 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001473 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001474 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001475 out += cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001476 }
1477 if (count != 0) {
1478 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1479 }
1480
1481 if (mExternalStylusDataPending) {
1482 if (timeout) {
1483 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1484 clearStylusDataPendingFlags();
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001485 mCurrentRawState = mLastRawState;
Harry Cutts45483602022-08-24 14:36:48 +00001486 ALOGD_IF(DEBUG_STYLUS_FUSION,
1487 "Timeout expired, synthesizing event with new stylus data");
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001488 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001489 out += cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001490 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1491 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1492 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1493 }
1494 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001495 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001496}
1497
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001498std::list<NotifyArgs> TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
1499 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001500 // Always start with a clean state.
1501 mCurrentCookedState.clear();
1502
1503 // Apply stylus buttons to current raw state.
1504 applyExternalStylusButtonState(when);
1505
1506 // Handle policy on initial down or hover events.
1507 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1508 mCurrentRawState.rawPointerData.pointerCount != 0;
1509
1510 uint32_t policyFlags = 0;
1511 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1512 if (initialDown || buttonsPressed) {
1513 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001514 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001515 getContext()->fadePointer();
1516 }
1517
1518 if (mParameters.wake) {
1519 policyFlags |= POLICY_FLAG_WAKE;
1520 }
1521 }
1522
1523 // Consume raw off-screen touches before cooking pointer data.
1524 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001525 bool consumed;
1526 out += consumeRawTouches(when, readTime, policyFlags, consumed /*byref*/);
1527 if (consumed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001528 mCurrentRawState.rawPointerData.clear();
1529 }
1530
1531 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1532 // with cooked pointer data that has the same ids and indices as the raw data.
1533 // The following code can use either the raw or cooked data, as needed.
1534 cookPointerData();
1535
1536 // Apply stylus pressure to current cooked state.
1537 applyExternalStylusTouchState(when);
1538
1539 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001540 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1541 mSource, mViewport.displayId, policyFlags,
1542 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001543
1544 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001545 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001546 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1547 uint32_t id = idBits.clearFirstMarkedBit();
1548 const RawPointerData::Pointer& pointer =
1549 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001550 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001551 mCurrentCookedState.stylusIdBits.markBit(id);
1552 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1553 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1554 mCurrentCookedState.fingerIdBits.markBit(id);
1555 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1556 mCurrentCookedState.mouseIdBits.markBit(id);
1557 }
1558 }
1559 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1560 uint32_t id = idBits.clearFirstMarkedBit();
1561 const RawPointerData::Pointer& pointer =
1562 mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhane5626962022-10-27 20:30:53 +00001563 if (isStylusToolType(pointer.toolType)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001564 mCurrentCookedState.stylusIdBits.markBit(id);
1565 }
1566 }
1567
1568 // Stylus takes precedence over all tools, then mouse, then finger.
1569 PointerUsage pointerUsage = mPointerUsage;
1570 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1571 mCurrentCookedState.mouseIdBits.clear();
1572 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001573 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001574 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1575 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001576 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001577 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1578 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001579 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001580 }
1581
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001582 out += dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001583 } else {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001584 if (!mCurrentMotionAborted) {
Prabir Pradhan9eb4e692022-04-27 13:19:15 +00001585 updateTouchSpots();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001586 out += dispatchButtonRelease(when, readTime, policyFlags);
1587 out += dispatchHoverExit(when, readTime, policyFlags);
1588 out += dispatchTouches(when, readTime, policyFlags);
1589 out += dispatchHoverEnterAndMove(when, readTime, policyFlags);
1590 out += dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001591 }
1592
1593 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1594 mCurrentMotionAborted = false;
1595 }
1596 }
1597
1598 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001599 out += synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(),
1600 mSource, mViewport.displayId, policyFlags,
1601 mLastCookedState.buttonState, mCurrentCookedState.buttonState);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001602
1603 // Clear some transient state.
1604 mCurrentRawState.rawVScroll = 0;
1605 mCurrentRawState.rawHScroll = 0;
1606
1607 // Copy current touch to last touch in preparation for the next cycle.
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001608 mLastRawState = mCurrentRawState;
1609 mLastCookedState = mCurrentCookedState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001610 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001611}
1612
Garfield Tanc734e4f2021-01-15 20:01:39 -08001613void TouchInputMapper::updateTouchSpots() {
1614 if (!mConfig.showTouches || mPointerController == nullptr) {
1615 return;
1616 }
1617
1618 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1619 // clear touch spots.
1620 if (mDeviceMode != DeviceMode::DIRECT &&
1621 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1622 return;
1623 }
1624
1625 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1626 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1627
1628 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001629 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords.cbegin(),
1630 mCurrentCookedState.cookedPointerData.idToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00001631 mCurrentCookedState.cookedPointerData.touchingIdBits,
1632 mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001633}
1634
1635bool TouchInputMapper::isTouchScreen() {
1636 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1637 mParameters.hasAssociatedDisplay;
1638}
1639
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001640void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001641 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus()) {
1642 // If any of the external buttons are already pressed by the touch device, ignore them.
1643 const int32_t pressedButtons = ~mCurrentRawState.buttonState & mExternalStylusState.buttons;
1644 const int32_t releasedButtons =
1645 mExternalStylusButtonsApplied & ~mExternalStylusState.buttons;
1646
1647 mCurrentRawState.buttonState |= pressedButtons;
1648 mCurrentRawState.buttonState &= ~releasedButtons;
1649
1650 mExternalStylusButtonsApplied |= pressedButtons;
1651 mExternalStylusButtonsApplied &= ~releasedButtons;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001652 }
1653}
1654
1655void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1656 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1657 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001658 if (!mFusedStylusPointerId || !currentPointerData.isTouching(*mFusedStylusPointerId)) {
1659 return;
1660 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001661
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001662 float pressure = lastPointerData.isTouching(*mFusedStylusPointerId)
1663 ? lastPointerData.pointerCoordsForId(*mFusedStylusPointerId)
1664 .getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)
1665 : 0.f;
1666 if (mExternalStylusState.pressure && *mExternalStylusState.pressure > 0.f) {
1667 pressure = *mExternalStylusState.pressure;
1668 }
1669 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(*mFusedStylusPointerId);
1670 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001671
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001672 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001673 PointerProperties& properties =
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001674 currentPointerData.editPointerPropertiesWithId(*mFusedStylusPointerId);
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001675 properties.toolType = mExternalStylusState.toolType;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001676 }
1677}
1678
1679bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001680 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001681 return false;
1682 }
1683
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001684 // Check if the stylus pointer has gone up.
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001685 if (mFusedStylusPointerId &&
1686 !state.rawPointerData.touchingIdBits.hasBit(*mFusedStylusPointerId)) {
Harry Cutts45483602022-08-24 14:36:48 +00001687 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus pointer is going up");
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001688 mFusedStylusPointerId.reset();
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001689 return false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001690 }
1691
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001692 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1693 state.rawPointerData.pointerCount != 0;
1694 if (!initialDown) {
1695 return false;
1696 }
1697
1698 if (!mExternalStylusState.pressure) {
1699 ALOGD_IF(DEBUG_STYLUS_FUSION, "Stylus does not support pressure, no pointer fusion needed");
1700 return false;
1701 }
1702
1703 if (*mExternalStylusState.pressure != 0.0f) {
1704 ALOGD_IF(DEBUG_STYLUS_FUSION, "Have both stylus and touch data, beginning fusion");
1705 mFusedStylusPointerId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1706 return false;
1707 }
1708
1709 if (timeout) {
1710 ALOGD_IF(DEBUG_STYLUS_FUSION, "Timeout expired, assuming touch is not a stylus.");
1711 mFusedStylusPointerId.reset();
1712 mExternalStylusFusionTimeout = LLONG_MAX;
1713 return false;
1714 }
1715
1716 // We are waiting for the external stylus to report a pressure value. Withhold touches from
1717 // being processed until we either get pressure data or timeout.
1718 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1719 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1720 }
1721 ALOGD_IF(DEBUG_STYLUS_FUSION,
1722 "No stylus data but stylus is connected, requesting timeout (%" PRId64 "ms)",
1723 mExternalStylusFusionTimeout);
1724 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1725 return true;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001726}
1727
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001728std::list<NotifyArgs> TouchInputMapper::timeoutExpired(nsecs_t when) {
1729 std::list<NotifyArgs> out;
Michael Wright227c5542020-07-02 18:30:52 +01001730 if (mDeviceMode == DeviceMode::POINTER) {
1731 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001732 // Since this is a synthetic event, we can consider its latency to be zero
1733 const nsecs_t readTime = when;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001734 out += dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001735 }
Michael Wright227c5542020-07-02 18:30:52 +01001736 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhan7d04c4b2022-10-28 19:23:26 +00001737 if (mExternalStylusFusionTimeout <= when) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001738 out += processRawTouches(true /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001739 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1740 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1741 }
1742 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001743 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001744}
1745
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001746std::list<NotifyArgs> TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1747 std::list<NotifyArgs> out;
Prabir Pradhan124ea442022-10-28 20:27:44 +00001748 const bool buttonsChanged = mExternalStylusState.buttons != state.buttons;
Prabir Pradhan3f7545f2022-10-19 16:56:39 +00001749 mExternalStylusState = state;
Prabir Pradhan8d9ba912022-11-11 22:26:33 +00001750 if (mFusedStylusPointerId || mExternalStylusFusionTimeout != LLONG_MAX || buttonsChanged) {
Prabir Pradhan124ea442022-10-28 20:27:44 +00001751 // The following three cases are handled here:
1752 // - We're in the middle of a fused stream of data;
1753 // - We're waiting on external stylus data before dispatching the initial down; or
1754 // - Only the button state, which is not reported through a specific pointer, has changed.
1755 // Go ahead and dispatch now that we have fresh stylus data.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001756 mExternalStylusDataPending = true;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001757 out += processRawTouches(false /*timeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001758 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001759 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001760}
1761
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001762std::list<NotifyArgs> TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime,
1763 uint32_t policyFlags, bool& outConsumed) {
1764 outConsumed = false;
1765 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001766 // Check for release of a virtual key.
1767 if (mCurrentVirtualKey.down) {
1768 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1769 // Pointer went up while virtual key was down.
1770 mCurrentVirtualKey.down = false;
1771 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001772 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1773 "VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1774 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001775 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1776 AKEY_EVENT_FLAG_FROM_SYSTEM |
1777 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001778 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001779 outConsumed = true;
1780 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001781 }
1782
1783 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1784 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1785 const RawPointerData::Pointer& pointer =
1786 mCurrentRawState.rawPointerData.pointerForId(id);
1787 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1788 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1789 // Pointer is still within the space of the virtual key.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001790 outConsumed = true;
1791 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001792 }
1793 }
1794
1795 // Pointer left virtual key area or another pointer also went down.
1796 // Send key cancellation but do not consume the touch yet.
1797 // This is useful when the user swipes through from the virtual key area
1798 // into the main display surface.
1799 mCurrentVirtualKey.down = false;
1800 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001801 ALOGD_IF(DEBUG_VIRTUAL_KEYS, "VirtualKeys: Canceling key: keyCode=%d, scanCode=%d",
1802 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001803 out.push_back(dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
1804 AKEY_EVENT_FLAG_FROM_SYSTEM |
1805 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1806 AKEY_EVENT_FLAG_CANCELED));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001807 }
1808 }
1809
1810 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1811 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1812 // Pointer just went down. Check for virtual key press or off-screen touches.
1813 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1814 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001815 // Skip checking whether the pointer is inside the physical frame if the device is in
1816 // unscaled mode.
1817 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1818 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001819 // If exactly one pointer went down, check for virtual key hit.
1820 // Otherwise we will drop the entire stroke.
1821 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1822 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1823 if (virtualKey) {
1824 mCurrentVirtualKey.down = true;
1825 mCurrentVirtualKey.downTime = when;
1826 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1827 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1828 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001829 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1830 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001831
1832 if (!mCurrentVirtualKey.ignored) {
Harry Cutts45483602022-08-24 14:36:48 +00001833 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
1834 "VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1835 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001836 out.push_back(dispatchVirtualKey(when, readTime, policyFlags,
1837 AKEY_EVENT_ACTION_DOWN,
1838 AKEY_EVENT_FLAG_FROM_SYSTEM |
1839 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001840 }
1841 }
1842 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001843 outConsumed = true;
1844 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001845 }
1846 }
1847
1848 // Disable all virtual key touches that happen within a short time interval of the
1849 // most recent touch within the screen area. The idea is to filter out stray
1850 // virtual key presses when interacting with the touch screen.
1851 //
1852 // Problems we're trying to solve:
1853 //
1854 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1855 // virtual key area that is implemented by a separate touch panel and accidentally
1856 // triggers a virtual key.
1857 //
1858 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1859 // area and accidentally triggers a virtual key. This often happens when virtual keys
1860 // are layed out below the screen near to where the on screen keyboard's space bar
1861 // is displayed.
1862 if (mConfig.virtualKeyQuietTime > 0 &&
1863 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001864 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001865 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001866 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001867}
1868
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001869NotifyKeyArgs TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime,
1870 uint32_t policyFlags, int32_t keyEventAction,
1871 int32_t keyEventFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001872 int32_t keyCode = mCurrentVirtualKey.keyCode;
1873 int32_t scanCode = mCurrentVirtualKey.scanCode;
1874 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001875 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001876 policyFlags |= POLICY_FLAG_VIRTUAL;
1877
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001878 return NotifyKeyArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
1879 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1880 keyEventFlags, keyCode, scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001881}
1882
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001883std::list<NotifyArgs> TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime,
1884 uint32_t policyFlags) {
1885 std::list<NotifyArgs> out;
lilinnan687e58f2022-07-19 16:00:50 +08001886 if (mCurrentMotionAborted) {
1887 // Current motion event was already aborted.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001888 return out;
lilinnan687e58f2022-07-19 16:00:50 +08001889 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001890 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1891 if (!currentIdBits.isEmpty()) {
1892 int32_t metaState = getContext()->getGlobalMetaState();
1893 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001894 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00001895 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
1896 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001897 mCurrentCookedState.cookedPointerData.pointerProperties,
1898 mCurrentCookedState.cookedPointerData.pointerCoords,
1899 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1900 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1901 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001902 mCurrentMotionAborted = true;
1903 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001904 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001905}
1906
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00001907// Updates pointer coords and properties for pointers with specified ids that have moved.
1908// Returns true if any of them changed.
1909static bool updateMovedPointers(const PropertiesArray& inProperties, CoordsArray& inCoords,
1910 const IdToIndexArray& inIdToIndex, PropertiesArray& outProperties,
1911 CoordsArray& outCoords, IdToIndexArray& outIdToIndex,
1912 BitSet32 idBits) {
1913 bool changed = false;
1914 while (!idBits.isEmpty()) {
1915 uint32_t id = idBits.clearFirstMarkedBit();
1916 uint32_t inIndex = inIdToIndex[id];
1917 uint32_t outIndex = outIdToIndex[id];
1918
1919 const PointerProperties& curInProperties = inProperties[inIndex];
1920 const PointerCoords& curInCoords = inCoords[inIndex];
1921 PointerProperties& curOutProperties = outProperties[outIndex];
1922 PointerCoords& curOutCoords = outCoords[outIndex];
1923
1924 if (curInProperties != curOutProperties) {
1925 curOutProperties.copyFrom(curInProperties);
1926 changed = true;
1927 }
1928
1929 if (curInCoords != curOutCoords) {
1930 curOutCoords.copyFrom(curInCoords);
1931 changed = true;
1932 }
1933 }
1934 return changed;
1935}
1936
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001937std::list<NotifyArgs> TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime,
1938 uint32_t policyFlags) {
1939 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001940 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1941 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1942 int32_t metaState = getContext()->getGlobalMetaState();
1943 int32_t buttonState = mCurrentCookedState.buttonState;
1944
1945 if (currentIdBits == lastIdBits) {
1946 if (!currentIdBits.isEmpty()) {
1947 // No pointer id changes so this is a move event.
1948 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001949 out.push_back(
1950 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE,
1951 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1952 mCurrentCookedState.cookedPointerData.pointerProperties,
1953 mCurrentCookedState.cookedPointerData.pointerCoords,
1954 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits,
1955 -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime,
1956 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001957 }
1958 } else {
1959 // There may be pointers going up and pointers going down and pointers moving
1960 // all at the same time.
1961 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1962 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1963 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1964 BitSet32 dispatchedIdBits(lastIdBits.value);
1965
1966 // Update last coordinates of pointers that have moved so that we observe the new
1967 // pointer positions at the same time as other pointers that have just gone up.
1968 bool moveNeeded =
1969 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1970 mCurrentCookedState.cookedPointerData.pointerCoords,
1971 mCurrentCookedState.cookedPointerData.idToIndex,
1972 mLastCookedState.cookedPointerData.pointerProperties,
1973 mLastCookedState.cookedPointerData.pointerCoords,
1974 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1975 if (buttonState != mLastCookedState.buttonState) {
1976 moveNeeded = true;
1977 }
1978
1979 // Dispatch pointer up events.
1980 while (!upIdBits.isEmpty()) {
1981 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001982 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001983 if (isCanceled) {
1984 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1985 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07001986 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
1987 AMOTION_EVENT_ACTION_POINTER_UP, 0,
1988 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState,
1989 buttonState, 0,
1990 mLastCookedState.cookedPointerData.pointerProperties,
1991 mLastCookedState.cookedPointerData.pointerCoords,
1992 mLastCookedState.cookedPointerData.idToIndex,
1993 dispatchedIdBits, upId, mOrientedXPrecision,
1994 mOrientedYPrecision, mDownTime,
1995 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001996 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001997 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001998 }
1999
2000 // Dispatch move events if any of the remaining pointers moved from their old locations.
2001 // Although applications receive new locations as part of individual pointer up
2002 // events, they do not generally handle them except when presented in a move event.
2003 if (moveNeeded && !moveIdBits.isEmpty()) {
2004 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002005 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2006 AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0,
2007 mCurrentCookedState.cookedPointerData.pointerProperties,
2008 mCurrentCookedState.cookedPointerData.pointerCoords,
2009 mCurrentCookedState.cookedPointerData.idToIndex,
2010 dispatchedIdBits, -1, mOrientedXPrecision,
2011 mOrientedYPrecision, mDownTime,
2012 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002013 }
2014
2015 // Dispatch pointer down events using the new pointer locations.
2016 while (!downIdBits.isEmpty()) {
2017 uint32_t downId = downIdBits.clearFirstMarkedBit();
2018 dispatchedIdBits.markBit(downId);
2019
2020 if (dispatchedIdBits.count() == 1) {
2021 // First pointer is going down. Set down time.
2022 mDownTime = when;
2023 }
2024
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002025 out.push_back(
2026 dispatchMotion(when, readTime, policyFlags, mSource,
2027 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState,
2028 0, mCurrentCookedState.cookedPointerData.pointerProperties,
2029 mCurrentCookedState.cookedPointerData.pointerCoords,
2030 mCurrentCookedState.cookedPointerData.idToIndex,
2031 dispatchedIdBits, downId, mOrientedXPrecision,
2032 mOrientedYPrecision, mDownTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002033 }
2034 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002035 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002036}
2037
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002038std::list<NotifyArgs> TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime,
2039 uint32_t policyFlags) {
2040 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002041 if (mSentHoverEnter &&
2042 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2043 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2044 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002045 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2046 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
2047 mLastCookedState.buttonState, 0,
2048 mLastCookedState.cookedPointerData.pointerProperties,
2049 mLastCookedState.cookedPointerData.pointerCoords,
2050 mLastCookedState.cookedPointerData.idToIndex,
2051 mLastCookedState.cookedPointerData.hoveringIdBits, -1,
2052 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2053 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002054 mSentHoverEnter = false;
2055 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002056 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002057}
2058
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002059std::list<NotifyArgs> TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2060 uint32_t policyFlags) {
2061 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002062 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2063 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2064 int32_t metaState = getContext()->getGlobalMetaState();
2065 if (!mSentHoverEnter) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002066 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2067 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
2068 mCurrentRawState.buttonState, 0,
2069 mCurrentCookedState.cookedPointerData.pointerProperties,
2070 mCurrentCookedState.cookedPointerData.pointerCoords,
2071 mCurrentCookedState.cookedPointerData.idToIndex,
2072 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2073 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2074 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002075 mSentHoverEnter = true;
2076 }
2077
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002078 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2079 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2080 mCurrentRawState.buttonState, 0,
2081 mCurrentCookedState.cookedPointerData.pointerProperties,
2082 mCurrentCookedState.cookedPointerData.pointerCoords,
2083 mCurrentCookedState.cookedPointerData.idToIndex,
2084 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2085 mOrientedXPrecision, mOrientedYPrecision, mDownTime,
2086 MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002087 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002088 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002089}
2090
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002091std::list<NotifyArgs> TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime,
2092 uint32_t policyFlags) {
2093 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002094 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2095 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2096 const int32_t metaState = getContext()->getGlobalMetaState();
2097 int32_t buttonState = mLastCookedState.buttonState;
2098 while (!releasedButtons.isEmpty()) {
2099 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2100 buttonState &= ~actionButton;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002101 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2102 AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
2103 metaState, buttonState, 0,
Prabir Pradhan211ba622022-10-31 21:09:21 +00002104 mLastCookedState.cookedPointerData.pointerProperties,
2105 mLastCookedState.cookedPointerData.pointerCoords,
2106 mLastCookedState.cookedPointerData.idToIndex, idBits, -1,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002107 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::dispatchButtonPress(nsecs_t when, nsecs_t readTime,
2114 uint32_t policyFlags) {
2115 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002116 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2117 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2118 const int32_t metaState = getContext()->getGlobalMetaState();
2119 int32_t buttonState = mLastCookedState.buttonState;
2120 while (!pressedButtons.isEmpty()) {
2121 int32_t actionButton = BitSet32::valueForBit(pressedButtons.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_PRESS, actionButton, 0, metaState,
2125 buttonState, 0,
2126 mCurrentCookedState.cookedPointerData.pointerProperties,
2127 mCurrentCookedState.cookedPointerData.pointerCoords,
2128 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2129 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
2135const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2136 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2137 return cookedPointerData.touchingIdBits;
2138 }
2139 return cookedPointerData.hoveringIdBits;
2140}
2141
2142void TouchInputMapper::cookPointerData() {
2143 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2144
2145 mCurrentCookedState.cookedPointerData.clear();
2146 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2147 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2148 mCurrentRawState.rawPointerData.hoveringIdBits;
2149 mCurrentCookedState.cookedPointerData.touchingIdBits =
2150 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002151 mCurrentCookedState.cookedPointerData.canceledIdBits =
2152 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002153
2154 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2155 mCurrentCookedState.buttonState = 0;
2156 } else {
2157 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2158 }
2159
2160 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002161 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002162 for (uint32_t i = 0; i < currentPointerCount; i++) {
2163 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2164
2165 // Size
2166 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2167 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002168 case Calibration::SizeCalibration::GEOMETRIC:
2169 case Calibration::SizeCalibration::DIAMETER:
2170 case Calibration::SizeCalibration::BOX:
2171 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002172 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2173 touchMajor = in.touchMajor;
2174 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2175 toolMajor = in.toolMajor;
2176 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2177 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2178 : in.touchMajor;
2179 } else if (mRawPointerAxes.touchMajor.valid) {
2180 toolMajor = touchMajor = in.touchMajor;
2181 toolMinor = touchMinor =
2182 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2183 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2184 : in.touchMajor;
2185 } else if (mRawPointerAxes.toolMajor.valid) {
2186 touchMajor = toolMajor = in.toolMajor;
2187 touchMinor = toolMinor =
2188 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2189 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2190 : in.toolMajor;
2191 } else {
2192 ALOG_ASSERT(false,
2193 "No touch or tool axes. "
2194 "Size calibration should have been resolved to NONE.");
2195 touchMajor = 0;
2196 touchMinor = 0;
2197 toolMajor = 0;
2198 toolMinor = 0;
2199 size = 0;
2200 }
2201
Siarhei Vishniakou24210882022-07-15 09:42:04 -07002202 if (mCalibration.sizeIsSummed && *mCalibration.sizeIsSummed) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002203 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2204 if (touchingCount > 1) {
2205 touchMajor /= touchingCount;
2206 touchMinor /= touchingCount;
2207 toolMajor /= touchingCount;
2208 toolMinor /= touchingCount;
2209 size /= touchingCount;
2210 }
2211 }
2212
Michael Wright227c5542020-07-02 18:30:52 +01002213 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002214 touchMajor *= mGeometricScale;
2215 touchMinor *= mGeometricScale;
2216 toolMajor *= mGeometricScale;
2217 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002218 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002219 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2220 touchMinor = touchMajor;
2221 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2222 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002223 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002224 touchMinor = touchMajor;
2225 toolMinor = toolMajor;
2226 }
2227
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002228 mCalibration.applySizeScaleAndBias(touchMajor);
2229 mCalibration.applySizeScaleAndBias(touchMinor);
2230 mCalibration.applySizeScaleAndBias(toolMajor);
2231 mCalibration.applySizeScaleAndBias(toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002232 size *= mSizeScale;
2233 break;
Siarhei Vishniakou07247342022-07-15 14:27:37 -07002234 case Calibration::SizeCalibration::DEFAULT:
2235 LOG_ALWAYS_FATAL("Resolution should not be 'DEFAULT' at this point");
2236 break;
2237 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002238 touchMajor = 0;
2239 touchMinor = 0;
2240 toolMajor = 0;
2241 toolMinor = 0;
2242 size = 0;
2243 break;
2244 }
2245
2246 // Pressure
2247 float pressure;
2248 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002249 case Calibration::PressureCalibration::PHYSICAL:
2250 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002251 pressure = in.pressure * mPressureScale;
2252 break;
2253 default:
2254 pressure = in.isHovering ? 0 : 1;
2255 break;
2256 }
2257
2258 // Tilt and Orientation
2259 float tilt;
2260 float orientation;
2261 if (mHaveTilt) {
2262 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2263 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002264 orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002265 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2266 } else {
2267 tilt = 0;
2268
2269 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002270 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002271 orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002272 break;
Michael Wright227c5542020-07-02 18:30:52 +01002273 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002274 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2275 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2276 if (c1 != 0 || c2 != 0) {
Prabir Pradhane2e10b42022-11-17 20:59:36 +00002277 orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002278 float confidence = hypotf(c1, c2);
2279 float scale = 1.0f + confidence / 16.0f;
2280 touchMajor *= scale;
2281 touchMinor /= scale;
2282 toolMajor *= scale;
2283 toolMinor /= scale;
2284 } else {
2285 orientation = 0;
2286 }
2287 break;
2288 }
2289 default:
2290 orientation = 0;
2291 }
2292 }
2293
2294 // Distance
2295 float distance;
2296 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002297 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002298 distance = in.distance * mDistanceScale;
2299 break;
2300 default:
2301 distance = 0;
2302 }
2303
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002304 // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
2305 vec2 transformed = {in.x, in.y};
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002306 mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
2307 transformed = mRawToDisplay.transform(transformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002308
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002309 // Write output coords.
2310 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2311 out.clear();
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002312 out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
2313 out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002314 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2315 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2316 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2317 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2318 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2319 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2320 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Prabir Pradhan64fd5202022-11-30 19:45:11 +00002321 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2322 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002323
Chris Ye364fdb52020-08-05 15:07:56 -07002324 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002325 uint32_t id = in.id;
2326 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2327 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2328 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
Prabir Pradhanea31d4f2022-11-10 20:48:01 +00002329 float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2330 float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002331 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2332 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2333 }
2334
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002335 // Write output properties.
2336 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002337 properties.clear();
2338 properties.id = id;
2339 properties.toolType = in.toolType;
2340
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002341 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002342 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002343 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002344 }
2345}
2346
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002347std::list<NotifyArgs> TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime,
2348 uint32_t policyFlags,
2349 PointerUsage pointerUsage) {
2350 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002351 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002352 out += abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002353 mPointerUsage = pointerUsage;
2354 }
2355
2356 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002357 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002358 out += dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002359 break;
Michael Wright227c5542020-07-02 18:30:52 +01002360 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002361 out += dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002362 break;
Michael Wright227c5542020-07-02 18:30:52 +01002363 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002364 out += dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002365 break;
Michael Wright227c5542020-07-02 18:30:52 +01002366 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002367 break;
2368 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002369 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002370}
2371
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002372std::list<NotifyArgs> TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime,
2373 uint32_t policyFlags) {
2374 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002375 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002376 case PointerUsage::GESTURES:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002377 out += abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002378 break;
Michael Wright227c5542020-07-02 18:30:52 +01002379 case PointerUsage::STYLUS:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002380 out += abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002381 break;
Michael Wright227c5542020-07-02 18:30:52 +01002382 case PointerUsage::MOUSE:
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002383 out += abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002384 break;
Michael Wright227c5542020-07-02 18:30:52 +01002385 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002386 break;
2387 }
2388
Michael Wright227c5542020-07-02 18:30:52 +01002389 mPointerUsage = PointerUsage::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002390 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002391}
2392
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002393std::list<NotifyArgs> TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime,
2394 uint32_t policyFlags,
2395 bool isTimeout) {
2396 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002397 // Update current gesture coordinates.
2398 bool cancelPreviousGesture, finishPreviousGesture;
2399 bool sendEvents =
2400 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2401 if (!sendEvents) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002402 return {};
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002403 }
2404 if (finishPreviousGesture) {
2405 cancelPreviousGesture = false;
2406 }
2407
2408 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002409 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002410 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002411 if (finishPreviousGesture || cancelPreviousGesture) {
2412 mPointerController->clearSpots();
2413 }
2414
Michael Wright227c5542020-07-02 18:30:52 +01002415 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00002416 mPointerController->setSpots(mPointerGesture.currentGestureCoords.cbegin(),
2417 mPointerGesture.currentGestureIdToIndex.cbegin(),
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002418 mPointerGesture.currentGestureIdBits,
2419 mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002420 }
2421 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002422 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002423 }
2424
2425 // Show or hide the pointer if needed.
2426 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002427 case PointerGesture::Mode::NEUTRAL:
2428 case PointerGesture::Mode::QUIET:
2429 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2430 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002431 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002432 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002433 }
2434 break;
Michael Wright227c5542020-07-02 18:30:52 +01002435 case PointerGesture::Mode::TAP:
2436 case PointerGesture::Mode::TAP_DRAG:
2437 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2438 case PointerGesture::Mode::HOVER:
2439 case PointerGesture::Mode::PRESS:
2440 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002441 // Unfade the pointer when the current gesture manipulates the
2442 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002443 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002444 break;
Michael Wright227c5542020-07-02 18:30:52 +01002445 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002446 // Fade the pointer when the current gesture manipulates a different
2447 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002448 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002449 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002450 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002451 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002452 }
2453 break;
2454 }
2455
2456 // Send events!
2457 int32_t metaState = getContext()->getGlobalMetaState();
2458 int32_t buttonState = mCurrentCookedState.buttonState;
Harry Cutts2800fb02022-09-15 13:49:23 +00002459 const MotionClassification classification =
2460 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE
2461 ? MotionClassification::TWO_FINGER_SWIPE
2462 : MotionClassification::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002463
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002464 uint32_t flags = 0;
2465
2466 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2467 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2468 }
2469
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002470 // Update last coordinates of pointers that have moved so that we observe the new
2471 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002472 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2473 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2474 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2475 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2476 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2477 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002478 bool moveNeeded = false;
2479 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2480 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2481 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2482 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2483 mPointerGesture.lastGestureIdBits.value);
2484 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2485 mPointerGesture.currentGestureCoords,
2486 mPointerGesture.currentGestureIdToIndex,
2487 mPointerGesture.lastGestureProperties,
2488 mPointerGesture.lastGestureCoords,
2489 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2490 if (buttonState != mLastCookedState.buttonState) {
2491 moveNeeded = true;
2492 }
2493 }
2494
2495 // Send motion events for all pointers that went up or were canceled.
2496 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2497 if (!dispatchedGestureIdBits.isEmpty()) {
2498 if (cancelPreviousGesture) {
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002499 const uint32_t cancelFlags = flags | AMOTION_EVENT_FLAG_CANCELED;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002500 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002501 AMOTION_EVENT_ACTION_CANCEL, 0, cancelFlags, metaState,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002502 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2503 mPointerGesture.lastGestureProperties,
2504 mPointerGesture.lastGestureCoords,
2505 mPointerGesture.lastGestureIdToIndex,
2506 dispatchedGestureIdBits, -1, 0, 0,
2507 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002508
2509 dispatchedGestureIdBits.clear();
2510 } else {
2511 BitSet32 upGestureIdBits;
2512 if (finishPreviousGesture) {
2513 upGestureIdBits = dispatchedGestureIdBits;
2514 } else {
2515 upGestureIdBits.value =
2516 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2517 }
2518 while (!upGestureIdBits.isEmpty()) {
2519 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2520
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002521 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2522 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState,
2523 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2524 mPointerGesture.lastGestureProperties,
2525 mPointerGesture.lastGestureCoords,
2526 mPointerGesture.lastGestureIdToIndex,
2527 dispatchedGestureIdBits, id, 0, 0,
2528 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002529
2530 dispatchedGestureIdBits.clearBit(id);
2531 }
2532 }
2533 }
2534
2535 // Send motion events for all pointers that moved.
2536 if (moveNeeded) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002537 out.push_back(
2538 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0,
2539 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2540 mPointerGesture.currentGestureProperties,
2541 mPointerGesture.currentGestureCoords,
2542 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1,
2543 0, 0, mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002544 }
2545
2546 // Send motion events for all pointers that went down.
2547 if (down) {
2548 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2549 ~dispatchedGestureIdBits.value);
2550 while (!downGestureIdBits.isEmpty()) {
2551 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2552 dispatchedGestureIdBits.markBit(id);
2553
2554 if (dispatchedGestureIdBits.count() == 1) {
2555 mPointerGesture.downTime = when;
2556 }
2557
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002558 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2559 AMOTION_EVENT_ACTION_POINTER_DOWN, 0, flags, metaState,
2560 buttonState, 0, mPointerGesture.currentGestureProperties,
2561 mPointerGesture.currentGestureCoords,
2562 mPointerGesture.currentGestureIdToIndex,
2563 dispatchedGestureIdBits, id, 0, 0,
2564 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002565 }
2566 }
2567
2568 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002569 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002570 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
2571 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2572 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2573 mPointerGesture.currentGestureProperties,
2574 mPointerGesture.currentGestureCoords,
2575 mPointerGesture.currentGestureIdToIndex,
2576 mPointerGesture.currentGestureIdBits, -1, 0, 0,
2577 mPointerGesture.downTime, MotionClassification::NONE));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002578 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2579 // Synthesize a hover move event after all pointers go up to indicate that
2580 // the pointer is hovering again even if the user is not currently touching
2581 // the touch pad. This ensures that a view will receive a fresh hover enter
2582 // event after a tap.
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002583 float x, y;
2584 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002585
2586 PointerProperties pointerProperties;
2587 pointerProperties.clear();
2588 pointerProperties.id = 0;
2589 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2590
2591 PointerCoords pointerCoords;
2592 pointerCoords.clear();
2593 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2594 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2595
2596 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002597 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
2598 mSource, displayId, policyFlags,
2599 AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags, metaState,
2600 buttonState, MotionClassification::NONE,
2601 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
2602 &pointerCoords, 0, 0, x, y, mPointerGesture.downTime,
2603 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002604 }
2605
2606 // Update state.
2607 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2608 if (!down) {
2609 mPointerGesture.lastGestureIdBits.clear();
2610 } else {
2611 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2612 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2613 uint32_t id = idBits.clearFirstMarkedBit();
2614 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2615 mPointerGesture.lastGestureProperties[index].copyFrom(
2616 mPointerGesture.currentGestureProperties[index]);
2617 mPointerGesture.lastGestureCoords[index].copyFrom(
2618 mPointerGesture.currentGestureCoords[index]);
2619 mPointerGesture.lastGestureIdToIndex[id] = index;
2620 }
2621 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002622 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002623}
2624
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002625std::list<NotifyArgs> TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime,
2626 uint32_t policyFlags) {
Harry Cutts2800fb02022-09-15 13:49:23 +00002627 const MotionClassification classification =
2628 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE
2629 ? MotionClassification::TWO_FINGER_SWIPE
2630 : MotionClassification::NONE;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002631 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002632 // Cancel previously dispatches pointers.
2633 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2634 int32_t metaState = getContext()->getGlobalMetaState();
2635 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002636 out.push_back(dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhanf5b4d7a2022-10-03 15:45:50 +00002637 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
2638 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002639 mPointerGesture.lastGestureProperties,
2640 mPointerGesture.lastGestureCoords,
2641 mPointerGesture.lastGestureIdToIndex,
2642 mPointerGesture.lastGestureIdBits, -1, 0, 0,
2643 mPointerGesture.downTime, classification));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002644 }
2645
2646 // Reset the current pointer gesture.
2647 mPointerGesture.reset();
2648 mPointerVelocityControl.reset();
2649
2650 // Remove any current spots.
2651 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002652 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002653 mPointerController->clearSpots();
2654 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07002655 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002656}
2657
2658bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2659 bool* outFinishPreviousGesture, bool isTimeout) {
2660 *outCancelPreviousGesture = false;
2661 *outFinishPreviousGesture = false;
2662
2663 // Handle TAP timeout.
2664 if (isTimeout) {
Harry Cutts45483602022-08-24 14:36:48 +00002665 ALOGD_IF(DEBUG_GESTURES, "Gestures: Processing timeout");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002666
Michael Wright227c5542020-07-02 18:30:52 +01002667 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002668 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2669 // The tap/drag timeout has not yet expired.
2670 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2671 mConfig.pointerGestureTapDragInterval);
2672 } else {
2673 // The tap is finished.
Harry Cutts45483602022-08-24 14:36:48 +00002674 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP finished");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002675 *outFinishPreviousGesture = true;
2676
2677 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002678 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002679 mPointerGesture.currentGestureIdBits.clear();
2680
2681 mPointerVelocityControl.reset();
2682 return true;
2683 }
2684 }
2685
2686 // We did not handle this timeout.
2687 return false;
2688 }
2689
2690 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2691 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2692
2693 // Update the velocity tracker.
2694 {
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002695 std::vector<float> positionsX;
2696 std::vector<float> positionsY;
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002697 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002698 uint32_t id = idBits.clearFirstMarkedBit();
2699 const RawPointerData::Pointer& pointer =
2700 mCurrentRawState.rawPointerData.pointerForId(id);
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002701 positionsX.push_back(pointer.x * mPointerXMovementScale);
2702 positionsY.push_back(pointer.y * mPointerYMovementScale);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002703 }
2704 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
Yeabkal Wubshit384ab0f2022-09-09 16:39:18 +00002705 {{AMOTION_EVENT_AXIS_X, positionsX},
2706 {AMOTION_EVENT_AXIS_Y, positionsY}});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002707 }
2708
2709 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2710 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002711 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2712 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2713 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002714 mPointerGesture.resetTap();
2715 }
2716
2717 // Pick a new active touch id if needed.
2718 // Choose an arbitrary pointer that just went down, if there is one.
2719 // Otherwise choose an arbitrary remaining pointer.
2720 // This guarantees we always have an active touch id when there is at least one pointer.
2721 // We keep the same active touch id for as long as possible.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002722 if (mPointerGesture.activeTouchId < 0) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002723 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002724 mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002725 mPointerGesture.firstTouchTime = when;
2726 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002727 } else if (!mCurrentCookedState.fingerIdBits.hasBit(mPointerGesture.activeTouchId)) {
2728 mPointerGesture.activeTouchId = !mCurrentCookedState.fingerIdBits.isEmpty()
2729 ? mCurrentCookedState.fingerIdBits.firstMarkedBit()
2730 : -1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002731 }
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002732 const int32_t& activeTouchId = mPointerGesture.activeTouchId;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002733
2734 // Switch states based on button and pointer state.
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002735 if (checkForTouchpadQuietTime(when)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002736 // Case 1: Quiet time. (QUIET)
Harry Cutts45483602022-08-24 14:36:48 +00002737 ALOGD_IF(DEBUG_GESTURES, "Gestures: QUIET for next %0.3fms",
2738 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) *
2739 0.000001f);
Michael Wright227c5542020-07-02 18:30:52 +01002740 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002741 *outFinishPreviousGesture = true;
2742 }
2743
2744 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002745 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002746 mPointerGesture.currentGestureIdBits.clear();
2747
2748 mPointerVelocityControl.reset();
2749 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2750 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2751 // The pointer follows the active touch point.
2752 // Emit DOWN, MOVE, UP events at the pointer location.
2753 //
2754 // Only the active touch matters; other fingers are ignored. This policy helps
2755 // to handle the case where the user places a second finger on the touch pad
2756 // to apply the necessary force to depress an integrated button below the surface.
2757 // We don't want the second finger to be delivered to applications.
2758 //
2759 // For this to work well, we need to make sure to track the pointer that is really
2760 // active. If the user first puts one finger down to click then adds another
2761 // finger to drag then the active pointer should switch to the finger that is
2762 // being dragged.
Harry Cutts45483602022-08-24 14:36:48 +00002763 ALOGD_IF(DEBUG_GESTURES,
2764 "Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, currentFingerCount=%d",
2765 activeTouchId, currentFingerCount);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002766 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002767 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002768 *outFinishPreviousGesture = true;
2769 mPointerGesture.activeGestureId = 0;
2770 }
2771
2772 // Switch pointers if needed.
2773 // Find the fastest pointer and follow it.
2774 if (activeTouchId >= 0 && currentFingerCount > 1) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002775 const auto [bestId, bestSpeed] = getFastestFinger();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002776 if (bestId >= 0 && bestId != activeTouchId) {
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002777 mPointerGesture.activeTouchId = bestId;
Harry Cutts45483602022-08-24 14:36:48 +00002778 ALOGD_IF(DEBUG_GESTURES,
2779 "Gestures: BUTTON_CLICK_OR_DRAG switched pointers, bestId=%d, "
2780 "bestSpeed=%0.3f",
2781 bestId, bestSpeed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002782 }
2783 }
2784
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002785 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002786 // When using spots, the click will occur at the position of the anchor
2787 // spot and all other spots will move there.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002788 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002789 } else {
2790 mPointerVelocityControl.reset();
2791 }
2792
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002793 float x, y;
2794 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002795
Michael Wright227c5542020-07-02 18:30:52 +01002796 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002797 mPointerGesture.currentGestureIdBits.clear();
2798 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2799 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2800 mPointerGesture.currentGestureProperties[0].clear();
2801 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2802 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2803 mPointerGesture.currentGestureCoords[0].clear();
2804 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2805 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2806 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2807 } else if (currentFingerCount == 0) {
2808 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002809 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002810 *outFinishPreviousGesture = true;
2811 }
2812
2813 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2814 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2815 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002816 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2817 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002818 lastFingerCount == 1) {
2819 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002820 float x, y;
2821 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002822 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2823 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Harry Cutts45483602022-08-24 14:36:48 +00002824 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002825
2826 mPointerGesture.tapUpTime = when;
2827 getContext()->requestTimeoutAtTime(when +
2828 mConfig.pointerGestureTapDragInterval);
2829
2830 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002831 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002832 mPointerGesture.currentGestureIdBits.clear();
2833 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2834 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2835 mPointerGesture.currentGestureProperties[0].clear();
2836 mPointerGesture.currentGestureProperties[0].id =
2837 mPointerGesture.activeGestureId;
2838 mPointerGesture.currentGestureProperties[0].toolType =
2839 AMOTION_EVENT_TOOL_TYPE_FINGER;
2840 mPointerGesture.currentGestureCoords[0].clear();
2841 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2842 mPointerGesture.tapX);
2843 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2844 mPointerGesture.tapY);
2845 mPointerGesture.currentGestureCoords[0]
2846 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2847
2848 tapped = true;
2849 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002850 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP, deltaX=%f, deltaY=%f",
2851 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002852 }
2853 } else {
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002854 if (DEBUG_GESTURES) {
2855 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2856 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2857 (when - mPointerGesture.tapDownTime) * 0.000001f);
2858 } else {
2859 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2860 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002861 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002862 }
2863 }
2864
2865 mPointerVelocityControl.reset();
2866
2867 if (!tapped) {
Harry Cutts45483602022-08-24 14:36:48 +00002868 ALOGD_IF(DEBUG_GESTURES, "Gestures: NEUTRAL");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002869 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002870 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002871 mPointerGesture.currentGestureIdBits.clear();
2872 }
2873 } else if (currentFingerCount == 1) {
2874 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2875 // The pointer follows the active touch point.
2876 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2877 // When in TAP_DRAG, emit MOVE events at the pointer location.
2878 ALOG_ASSERT(activeTouchId >= 0);
2879
Michael Wright227c5542020-07-02 18:30:52 +01002880 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2881 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002882 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002883 float x, y;
2884 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002885 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2886 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002887 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002888 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002889 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2890 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002891 }
2892 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002893 ALOGD_IF(DEBUG_GESTURES, "Gestures: Not a TAP_DRAG, %0.3fms time since up",
2894 (when - mPointerGesture.tapUpTime) * 0.000001f);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002895 }
Michael Wright227c5542020-07-02 18:30:52 +01002896 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2897 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002898 }
2899
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002900 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002901 // When using spots, the hover or drag will occur at the position of the anchor spot.
Harry Cutts714d1ad2022-08-24 16:36:43 +00002902 moveMousePointerFromPointerDelta(when, activeTouchId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002903 } else {
2904 mPointerVelocityControl.reset();
2905 }
2906
2907 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002908 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Harry Cutts45483602022-08-24 14:36:48 +00002909 ALOGD_IF(DEBUG_GESTURES, "Gestures: TAP_DRAG");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002910 down = true;
2911 } else {
Harry Cutts45483602022-08-24 14:36:48 +00002912 ALOGD_IF(DEBUG_GESTURES, "Gestures: HOVER");
Michael Wright227c5542020-07-02 18:30:52 +01002913 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002914 *outFinishPreviousGesture = true;
2915 }
2916 mPointerGesture.activeGestureId = 0;
2917 down = false;
2918 }
2919
Prabir Pradhande69f8a2021-11-18 16:40:34 +00002920 float x, y;
2921 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002922
2923 mPointerGesture.currentGestureIdBits.clear();
2924 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2925 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2926 mPointerGesture.currentGestureProperties[0].clear();
2927 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2928 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2929 mPointerGesture.currentGestureCoords[0].clear();
2930 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2931 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2932 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2933 down ? 1.0f : 0.0f);
2934
2935 if (lastFingerCount == 0 && currentFingerCount != 0) {
2936 mPointerGesture.resetTap();
2937 mPointerGesture.tapDownTime = when;
2938 mPointerGesture.tapX = x;
2939 mPointerGesture.tapY = y;
2940 }
2941 } else {
2942 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002943 prepareMultiFingerPointerGestures(when, outCancelPreviousGesture, outFinishPreviousGesture);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002944 }
2945
2946 mPointerController->setButtonState(mCurrentRawState.buttonState);
2947
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08002948 if (DEBUG_GESTURES) {
2949 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
2950 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
2951 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
2952 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
2953 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
2954 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
2955 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
2956 uint32_t id = idBits.clearFirstMarkedBit();
2957 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2958 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
2959 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
2960 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
2961 "x=%0.3f, y=%0.3f, pressure=%0.3f",
2962 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
2963 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
2964 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
2965 }
2966 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
2967 uint32_t id = idBits.clearFirstMarkedBit();
2968 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
2969 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
2970 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
2971 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
2972 "x=%0.3f, y=%0.3f, pressure=%0.3f",
2973 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
2974 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
2975 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
2976 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002977 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002978 return true;
2979}
2980
Harry Cuttsbea6ce52022-10-14 15:17:30 +00002981bool TouchInputMapper::checkForTouchpadQuietTime(nsecs_t when) {
2982 if (mPointerGesture.activeTouchId < 0) {
2983 mPointerGesture.resetQuietTime();
2984 return false;
2985 }
2986
2987 if (when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval) {
2988 return true;
2989 }
2990
2991 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2992 bool isQuietTime = false;
2993 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2994 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2995 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
2996 currentFingerCount < 2) {
2997 // Enter quiet time when exiting swipe or freeform state.
2998 // This is to prevent accidentally entering the hover state and flinging the
2999 // pointer when finishing a swipe and there is still one pointer left onscreen.
3000 isQuietTime = true;
3001 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
3002 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
3003 // Enter quiet time when releasing the button and there are still two or more
3004 // fingers down. This may indicate that one finger was used to press the button
3005 // but it has not gone up yet.
3006 isQuietTime = true;
3007 }
3008 if (isQuietTime) {
3009 mPointerGesture.quietTime = when;
3010 }
3011 return isQuietTime;
3012}
3013
3014std::pair<int32_t, float> TouchInputMapper::getFastestFinger() {
3015 int32_t bestId = -1;
3016 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
3017 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
3018 uint32_t id = idBits.clearFirstMarkedBit();
3019 std::optional<float> vx =
3020 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
3021 std::optional<float> vy =
3022 mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
3023 if (vx && vy) {
3024 float speed = hypotf(*vx, *vy);
3025 if (speed > bestSpeed) {
3026 bestId = id;
3027 bestSpeed = speed;
3028 }
3029 }
3030 }
3031 return std::make_pair(bestId, bestSpeed);
3032}
3033
3034void TouchInputMapper::prepareMultiFingerPointerGestures(nsecs_t when, bool* cancelPreviousGesture,
3035 bool* finishPreviousGesture) {
3036 // We need to provide feedback for each finger that goes down so we cannot wait for the fingers
3037 // to move before deciding what to do.
3038 //
3039 // The ambiguous case is deciding what to do when there are two fingers down but they have not
3040 // moved enough to determine whether they are part of a drag or part of a freeform gesture, or
3041 // just a press or long-press at the pointer location.
3042 //
3043 // When there are two fingers we start with the PRESS hypothesis and we generate a down at the
3044 // pointer location.
3045 //
3046 // When the two fingers move enough or when additional fingers are added, we make a decision to
3047 // transition into SWIPE or FREEFORM mode accordingly.
3048 const int32_t activeTouchId = mPointerGesture.activeTouchId;
3049 ALOG_ASSERT(activeTouchId >= 0);
3050
3051 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
3052 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
3053 bool settled =
3054 when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
3055 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3056 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3057 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3058 *finishPreviousGesture = true;
3059 } else if (!settled && currentFingerCount > lastFingerCount) {
3060 // Additional pointers have gone down but not yet settled.
3061 // Reset the gesture.
3062 ALOGD_IF(DEBUG_GESTURES,
3063 "Gestures: Resetting gesture since additional pointers went down for "
3064 "MULTITOUCH, settle time remaining %0.3fms",
3065 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3066 when) * 0.000001f);
3067 *cancelPreviousGesture = true;
3068 } else {
3069 // Continue previous gesture.
3070 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3071 }
3072
3073 if (*finishPreviousGesture || *cancelPreviousGesture) {
3074 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
3075 mPointerGesture.activeGestureId = 0;
3076 mPointerGesture.referenceIdBits.clear();
3077 mPointerVelocityControl.reset();
3078
3079 // Use the centroid and pointer location as the reference points for the gesture.
3080 ALOGD_IF(DEBUG_GESTURES,
3081 "Gestures: Using centroid as reference for MULTITOUCH, settle time remaining "
3082 "%0.3fms",
3083 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3084 when) * 0.000001f);
3085 mCurrentRawState.rawPointerData
3086 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3087 &mPointerGesture.referenceTouchY);
3088 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3089 &mPointerGesture.referenceGestureY);
3090 }
3091
3092 // Clear the reference deltas for fingers not yet included in the reference calculation.
3093 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3094 ~mPointerGesture.referenceIdBits.value);
3095 !idBits.isEmpty();) {
3096 uint32_t id = idBits.clearFirstMarkedBit();
3097 mPointerGesture.referenceDeltas[id].dx = 0;
3098 mPointerGesture.referenceDeltas[id].dy = 0;
3099 }
3100 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3101
3102 // Add delta for all fingers and calculate a common movement delta.
3103 int32_t commonDeltaRawX = 0, commonDeltaRawY = 0;
3104 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3105 mCurrentCookedState.fingerIdBits.value);
3106 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3107 bool first = (idBits == commonIdBits);
3108 uint32_t id = idBits.clearFirstMarkedBit();
3109 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3110 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3111 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3112 delta.dx += cpd.x - lpd.x;
3113 delta.dy += cpd.y - lpd.y;
3114
3115 if (first) {
3116 commonDeltaRawX = delta.dx;
3117 commonDeltaRawY = delta.dy;
3118 } else {
3119 commonDeltaRawX = calculateCommonVector(commonDeltaRawX, delta.dx);
3120 commonDeltaRawY = calculateCommonVector(commonDeltaRawY, delta.dy);
3121 }
3122 }
3123
3124 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
3125 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
3126 float dist[MAX_POINTER_ID + 1];
3127 int32_t distOverThreshold = 0;
3128 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3129 uint32_t id = idBits.clearFirstMarkedBit();
3130 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3131 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3132 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3133 distOverThreshold += 1;
3134 }
3135 }
3136
3137 // Only transition when at least two pointers have moved further than
3138 // the minimum distance threshold.
3139 if (distOverThreshold >= 2) {
3140 if (currentFingerCount > 2) {
3141 // There are more than two pointers, switch to FREEFORM.
3142 ALOGD_IF(DEBUG_GESTURES,
3143 "Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3144 currentFingerCount);
3145 *cancelPreviousGesture = true;
3146 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3147 } else {
3148 // There are exactly two pointers.
3149 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3150 uint32_t id1 = idBits.clearFirstMarkedBit();
3151 uint32_t id2 = idBits.firstMarkedBit();
3152 const RawPointerData::Pointer& p1 =
3153 mCurrentRawState.rawPointerData.pointerForId(id1);
3154 const RawPointerData::Pointer& p2 =
3155 mCurrentRawState.rawPointerData.pointerForId(id2);
3156 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3157 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3158 // There are two pointers but they are too far apart for a SWIPE,
3159 // switch to FREEFORM.
3160 ALOGD_IF(DEBUG_GESTURES,
3161 "Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3162 mutualDistance, mPointerGestureMaxSwipeWidth);
3163 *cancelPreviousGesture = true;
3164 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3165 } else {
3166 // There are two pointers. Wait for both pointers to start moving
3167 // before deciding whether this is a SWIPE or FREEFORM gesture.
3168 float dist1 = dist[id1];
3169 float dist2 = dist[id2];
3170 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3171 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3172 // Calculate the dot product of the displacement vectors.
3173 // When the vectors are oriented in approximately the same direction,
3174 // the angle betweeen them is near zero and the cosine of the angle
3175 // approaches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3176 // mag(v2).
3177 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3178 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3179 float dx1 = delta1.dx * mPointerXZoomScale;
3180 float dy1 = delta1.dy * mPointerYZoomScale;
3181 float dx2 = delta2.dx * mPointerXZoomScale;
3182 float dy2 = delta2.dy * mPointerYZoomScale;
3183 float dot = dx1 * dx2 + dy1 * dy2;
3184 float cosine = dot / (dist1 * dist2); // denominator always > 0
3185 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3186 // Pointers are moving in the same direction. Switch to SWIPE.
3187 ALOGD_IF(DEBUG_GESTURES,
3188 "Gestures: PRESS transitioned to SWIPE, "
3189 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3190 "cosine %0.3f >= %0.3f",
3191 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3192 mConfig.pointerGestureMultitouchMinDistance, cosine,
3193 mConfig.pointerGestureSwipeTransitionAngleCosine);
3194 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
3195 } else {
3196 // Pointers are moving in different directions. Switch to FREEFORM.
3197 ALOGD_IF(DEBUG_GESTURES,
3198 "Gestures: PRESS transitioned to FREEFORM, "
3199 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3200 "cosine %0.3f < %0.3f",
3201 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3202 mConfig.pointerGestureMultitouchMinDistance, cosine,
3203 mConfig.pointerGestureSwipeTransitionAngleCosine);
3204 *cancelPreviousGesture = true;
3205 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3206 }
3207 }
3208 }
3209 }
3210 }
3211 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3212 // Switch from SWIPE to FREEFORM if additional pointers go down.
3213 // Cancel previous gesture.
3214 if (currentFingerCount > 2) {
3215 ALOGD_IF(DEBUG_GESTURES,
3216 "Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3217 currentFingerCount);
3218 *cancelPreviousGesture = true;
3219 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
3220 }
3221 }
3222
3223 // Move the reference points based on the overall group motion of the fingers
3224 // except in PRESS mode while waiting for a transition to occur.
3225 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
3226 (commonDeltaRawX || commonDeltaRawY)) {
3227 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3228 uint32_t id = idBits.clearFirstMarkedBit();
3229 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3230 delta.dx = 0;
3231 delta.dy = 0;
3232 }
3233
3234 mPointerGesture.referenceTouchX += commonDeltaRawX;
3235 mPointerGesture.referenceTouchY += commonDeltaRawY;
3236
3237 float commonDeltaX = commonDeltaRawX * mPointerXMovementScale;
3238 float commonDeltaY = commonDeltaRawY * mPointerYMovementScale;
3239
3240 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
3241 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3242
3243 mPointerGesture.referenceGestureX += commonDeltaX;
3244 mPointerGesture.referenceGestureY += commonDeltaY;
3245 }
3246
3247 // Report gestures.
3248 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3249 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3250 // PRESS or SWIPE mode.
3251 ALOGD_IF(DEBUG_GESTURES,
3252 "Gestures: PRESS or SWIPE activeTouchId=%d, activeGestureId=%d, "
3253 "currentTouchPointerCount=%d",
3254 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3255 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3256
3257 mPointerGesture.currentGestureIdBits.clear();
3258 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3259 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3260 mPointerGesture.currentGestureProperties[0].clear();
3261 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3262 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3263 mPointerGesture.currentGestureCoords[0].clear();
3264 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3265 mPointerGesture.referenceGestureX);
3266 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3267 mPointerGesture.referenceGestureY);
3268 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3269 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
3270 float xOffset = static_cast<float>(commonDeltaRawX) /
3271 (mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue);
3272 float yOffset = static_cast<float>(commonDeltaRawY) /
3273 (mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue);
3274 mPointerGesture.currentGestureCoords[0]
3275 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_X_OFFSET, xOffset);
3276 mPointerGesture.currentGestureCoords[0]
3277 .setAxisValue(AMOTION_EVENT_AXIS_GESTURE_Y_OFFSET, yOffset);
3278 }
3279 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
3280 // FREEFORM mode.
3281 ALOGD_IF(DEBUG_GESTURES,
3282 "Gestures: FREEFORM activeTouchId=%d, activeGestureId=%d, "
3283 "currentTouchPointerCount=%d",
3284 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3285 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3286
3287 mPointerGesture.currentGestureIdBits.clear();
3288
3289 BitSet32 mappedTouchIdBits;
3290 BitSet32 usedGestureIdBits;
3291 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
3292 // Initially, assign the active gesture id to the active touch point
3293 // if there is one. No other touch id bits are mapped yet.
3294 if (!*cancelPreviousGesture) {
3295 mappedTouchIdBits.markBit(activeTouchId);
3296 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3297 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3298 mPointerGesture.activeGestureId;
3299 } else {
3300 mPointerGesture.activeGestureId = -1;
3301 }
3302 } else {
3303 // Otherwise, assume we mapped all touches from the previous frame.
3304 // Reuse all mappings that are still applicable.
3305 mappedTouchIdBits.value =
3306 mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value;
3307 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3308
3309 // Check whether we need to choose a new active gesture id because the
3310 // current went went up.
3311 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3312 ~mCurrentCookedState.fingerIdBits.value);
3313 !upTouchIdBits.isEmpty();) {
3314 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3315 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3316 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3317 mPointerGesture.activeGestureId = -1;
3318 break;
3319 }
3320 }
3321 }
3322
3323 ALOGD_IF(DEBUG_GESTURES,
3324 "Gestures: FREEFORM follow up mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3325 "activeGestureId=%d",
3326 mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId);
3327
3328 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3329 for (uint32_t i = 0; i < currentFingerCount; i++) {
3330 uint32_t touchId = idBits.clearFirstMarkedBit();
3331 uint32_t gestureId;
3332 if (!mappedTouchIdBits.hasBit(touchId)) {
3333 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3334 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3335 ALOGD_IF(DEBUG_GESTURES,
3336 "Gestures: FREEFORM new mapping for touch id %d -> gesture id %d", touchId,
3337 gestureId);
3338 } else {
3339 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3340 ALOGD_IF(DEBUG_GESTURES,
3341 "Gestures: FREEFORM existing mapping for touch id %d -> gesture id %d",
3342 touchId, gestureId);
3343 }
3344 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3345 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3346
3347 const RawPointerData::Pointer& pointer =
3348 mCurrentRawState.rawPointerData.pointerForId(touchId);
3349 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3350 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3351 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3352
3353 mPointerGesture.currentGestureProperties[i].clear();
3354 mPointerGesture.currentGestureProperties[i].id = gestureId;
3355 mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3356 mPointerGesture.currentGestureCoords[i].clear();
3357 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_X,
3358 mPointerGesture.referenceGestureX +
3359 deltaX);
3360 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_Y,
3361 mPointerGesture.referenceGestureY +
3362 deltaY);
3363 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
3364 }
3365
3366 if (mPointerGesture.activeGestureId < 0) {
3367 mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit();
3368 ALOGD_IF(DEBUG_GESTURES, "Gestures: FREEFORM new activeGestureId=%d",
3369 mPointerGesture.activeGestureId);
3370 }
3371 }
3372}
3373
Harry Cutts714d1ad2022-08-24 16:36:43 +00003374void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
3375 const RawPointerData::Pointer& currentPointer =
3376 mCurrentRawState.rawPointerData.pointerForId(pointerId);
3377 const RawPointerData::Pointer& lastPointer =
3378 mLastRawState.rawPointerData.pointerForId(pointerId);
3379 float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
3380 float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
3381
3382 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
3383 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3384
3385 mPointerController->move(deltaX, deltaY);
3386}
3387
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003388std::list<NotifyArgs> TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime,
3389 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003390 mPointerSimple.currentCoords.clear();
3391 mPointerSimple.currentProperties.clear();
3392
3393 bool down, hovering;
3394 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3395 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3396 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003397 mPointerController
3398 ->setPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3399 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003400
3401 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3402 down = !hovering;
3403
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003404 float x, y;
3405 mPointerController->getPosition(&x, &y);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003406 mPointerSimple.currentCoords.copyFrom(
3407 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3408 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3409 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3410 mPointerSimple.currentProperties.id = 0;
3411 mPointerSimple.currentProperties.toolType =
3412 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3413 } else {
3414 down = false;
3415 hovering = false;
3416 }
3417
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003418 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003419}
3420
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003421std::list<NotifyArgs> TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime,
3422 uint32_t policyFlags) {
3423 return abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003424}
3425
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003426std::list<NotifyArgs> TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime,
3427 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003428 mPointerSimple.currentCoords.clear();
3429 mPointerSimple.currentProperties.clear();
3430
3431 bool down, hovering;
3432 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3433 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003434 if (mLastCookedState.mouseIdBits.hasBit(id)) {
Harry Cutts714d1ad2022-08-24 16:36:43 +00003435 moveMousePointerFromPointerDelta(when, id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003436 } else {
3437 mPointerVelocityControl.reset();
3438 }
3439
3440 down = isPointerDown(mCurrentRawState.buttonState);
3441 hovering = !down;
3442
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003443 float x, y;
3444 mPointerController->getPosition(&x, &y);
Harry Cutts714d1ad2022-08-24 16:36:43 +00003445 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003446 mPointerSimple.currentCoords.copyFrom(
3447 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3448 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3449 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3450 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3451 hovering ? 0.0f : 1.0f);
3452 mPointerSimple.currentProperties.id = 0;
3453 mPointerSimple.currentProperties.toolType =
3454 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3455 } else {
3456 mPointerVelocityControl.reset();
3457
3458 down = false;
3459 hovering = false;
3460 }
3461
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003462 return dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003463}
3464
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003465std::list<NotifyArgs> TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime,
3466 uint32_t policyFlags) {
3467 std::list<NotifyArgs> out = abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003468
3469 mPointerVelocityControl.reset();
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003470
3471 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003472}
3473
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003474std::list<NotifyArgs> TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime,
3475 uint32_t policyFlags, bool down,
3476 bool hovering) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003477 LOG_ALWAYS_FATAL_IF(mDeviceMode != DeviceMode::POINTER,
3478 "%s cannot be used when the device is not in POINTER mode.", __func__);
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003479 std::list<NotifyArgs> out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003480 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003481
3482 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003483 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003484 mPointerController->clearSpots();
3485 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003486 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003487 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003488 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003489 }
Garfield Tan9514d782020-11-10 16:37:23 -08003490 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003491
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003492 float xCursorPosition, yCursorPosition;
3493 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003494
3495 if (mPointerSimple.down && !down) {
3496 mPointerSimple.down = false;
3497
3498 // Send up.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003499 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3500 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0,
3501 0, metaState, mLastRawState.buttonState,
3502 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3503 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3504 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3505 yCursorPosition, mPointerSimple.downTime,
3506 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003507 }
3508
3509 if (mPointerSimple.hovering && !hovering) {
3510 mPointerSimple.hovering = false;
3511
3512 // Send hover exit.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003513 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3514 mSource, displayId, policyFlags,
3515 AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3516 mLastRawState.buttonState, MotionClassification::NONE,
3517 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3518 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3519 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3520 yCursorPosition, mPointerSimple.downTime,
3521 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003522 }
3523
3524 if (down) {
3525 if (!mPointerSimple.down) {
3526 mPointerSimple.down = true;
3527 mPointerSimple.downTime = when;
3528
3529 // Send down.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003530 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3531 mSource, displayId, policyFlags,
3532 AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState,
3533 mCurrentRawState.buttonState, MotionClassification::NONE,
3534 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3535 &mPointerSimple.currentProperties,
3536 &mPointerSimple.currentCoords, mOrientedXPrecision,
3537 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3538 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003539 }
3540
3541 // Send move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003542 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3543 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE,
3544 0, 0, metaState, mCurrentRawState.buttonState,
3545 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3546 &mPointerSimple.currentProperties,
3547 &mPointerSimple.currentCoords, mOrientedXPrecision,
3548 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3549 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003550 }
3551
3552 if (hovering) {
3553 if (!mPointerSimple.hovering) {
3554 mPointerSimple.hovering = true;
3555
3556 // Send hover enter.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003557 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3558 mSource, displayId, policyFlags,
3559 AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
3560 mCurrentRawState.buttonState, MotionClassification::NONE,
3561 AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3562 &mPointerSimple.currentProperties,
3563 &mPointerSimple.currentCoords, mOrientedXPrecision,
3564 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3565 mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003566 }
3567
3568 // Send hover move.
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003569 out.push_back(
3570 NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3571 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3572 metaState, mCurrentRawState.buttonState,
3573 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3574 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3575 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3576 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003577 }
3578
3579 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3580 float vscroll = mCurrentRawState.rawVScroll;
3581 float hscroll = mCurrentRawState.rawHScroll;
3582 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3583 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3584
3585 // Send scroll.
3586 PointerCoords pointerCoords;
3587 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3588 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3589 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3590
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003591 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3592 mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL,
3593 0, 0, metaState, mCurrentRawState.buttonState,
3594 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3595 &mPointerSimple.currentProperties, &pointerCoords,
3596 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3597 yCursorPosition, mPointerSimple.downTime,
3598 /* videoFrames */ {}));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003599 }
3600
3601 // Save state.
3602 if (down || hovering) {
3603 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3604 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003605 mPointerSimple.displayId = displayId;
3606 mPointerSimple.source = mSource;
3607 mPointerSimple.lastCursorX = xCursorPosition;
3608 mPointerSimple.lastCursorY = yCursorPosition;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003609 } else {
3610 mPointerSimple.reset();
3611 }
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003612 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003613}
3614
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003615std::list<NotifyArgs> TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime,
3616 uint32_t policyFlags) {
Prabir Pradhanb80b6c02022-11-02 20:05:13 +00003617 std::list<NotifyArgs> out;
3618 if (mPointerSimple.down || mPointerSimple.hovering) {
3619 int32_t metaState = getContext()->getGlobalMetaState();
3620 out.push_back(NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
3621 mPointerSimple.source, mPointerSimple.displayId, policyFlags,
3622 AMOTION_EVENT_ACTION_CANCEL, 0, AMOTION_EVENT_FLAG_CANCELED,
3623 metaState, mLastRawState.buttonState,
3624 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3625 &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
3626 mOrientedXPrecision, mOrientedYPrecision,
3627 mPointerSimple.lastCursorX, mPointerSimple.lastCursorY,
3628 mPointerSimple.downTime,
3629 /* videoFrames */ {}));
3630 if (mPointerController != nullptr) {
3631 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
3632 }
3633 }
3634 mPointerSimple.reset();
3635 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003636}
3637
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003638NotifyMotionArgs TouchInputMapper::dispatchMotion(
3639 nsecs_t when, nsecs_t readTime, uint32_t policyFlags, uint32_t source, int32_t action,
3640 int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState,
Prabir Pradhand6ccedb2022-09-27 21:04:06 +00003641 int32_t edgeFlags, const PropertiesArray& properties, const CoordsArray& coords,
3642 const IdToIndexArray& idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision,
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003643 float yPrecision, nsecs_t downTime, MotionClassification classification) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003644 PointerCoords pointerCoords[MAX_POINTERS];
3645 PointerProperties pointerProperties[MAX_POINTERS];
3646 uint32_t pointerCount = 0;
3647 while (!idBits.isEmpty()) {
3648 uint32_t id = idBits.clearFirstMarkedBit();
3649 uint32_t index = idToIndex[id];
3650 pointerProperties[pointerCount].copyFrom(properties[index]);
3651 pointerCoords[pointerCount].copyFrom(coords[index]);
3652
3653 if (changedId >= 0 && id == uint32_t(changedId)) {
3654 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3655 }
3656
3657 pointerCount += 1;
3658 }
3659
3660 ALOG_ASSERT(pointerCount != 0);
3661
3662 if (changedId >= 0 && pointerCount == 1) {
3663 // Replace initial down and final up action.
3664 // We can compare the action without masking off the changed pointer index
3665 // because we know the index is 0.
3666 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3667 action = AMOTION_EVENT_ACTION_DOWN;
3668 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003669 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3670 action = AMOTION_EVENT_ACTION_CANCEL;
3671 } else {
3672 action = AMOTION_EVENT_ACTION_UP;
3673 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003674 } else {
3675 // Can't happen.
3676 ALOG_ASSERT(false);
3677 }
3678 }
3679 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3680 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003681 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhande69f8a2021-11-18 16:40:34 +00003682 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003683 }
3684 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3685 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003686 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003687 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003688 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003689 return NotifyMotionArgs(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3690 policyFlags, action, actionButton, flags, metaState, buttonState,
3691 classification, edgeFlags, pointerCount, pointerProperties,
3692 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3693 downTime, std::move(frames));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003694}
3695
Siarhei Vishniakou2935db72022-09-22 13:35:22 -07003696std::list<NotifyArgs> TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3697 std::list<NotifyArgs> out;
3698 out += abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3699 out += abortTouches(when, readTime, 0 /* policyFlags*/);
3700 return out;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003701}
3702
Prabir Pradhan1728b212021-10-19 16:00:03 -07003703bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003704 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003705 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan675f25a2022-11-10 22:04:07 +00003706 isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003707}
3708
3709const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3710 for (const VirtualKey& virtualKey : mVirtualKeys) {
Harry Cutts45483602022-08-24 14:36:48 +00003711 ALOGD_IF(DEBUG_VIRTUAL_KEYS,
3712 "VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3713 "left=%d, top=%d, right=%d, bottom=%d",
3714 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft,
3715 virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003716
3717 if (virtualKey.isHit(x, y)) {
3718 return &virtualKey;
3719 }
3720 }
3721
3722 return nullptr;
3723}
3724
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003725void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3726 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3727 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003728
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003729 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003730
3731 if (currentPointerCount == 0) {
3732 // No pointers to assign.
3733 return;
3734 }
3735
3736 if (lastPointerCount == 0) {
3737 // All pointers are new.
3738 for (uint32_t i = 0; i < currentPointerCount; i++) {
3739 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003740 current.rawPointerData.pointers[i].id = id;
3741 current.rawPointerData.idToIndex[id] = i;
3742 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003743 }
3744 return;
3745 }
3746
3747 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003748 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003749 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003750 uint32_t id = last.rawPointerData.pointers[0].id;
3751 current.rawPointerData.pointers[0].id = id;
3752 current.rawPointerData.idToIndex[id] = 0;
3753 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003754 return;
3755 }
3756
3757 // General case.
3758 // We build a heap of squared euclidean distances between current and last pointers
3759 // associated with the current and last pointer indices. Then, we find the best
3760 // match (by distance) for each current pointer.
3761 // The pointers must have the same tool type but it is possible for them to
3762 // transition from hovering to touching or vice-versa while retaining the same id.
3763 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3764
3765 uint32_t heapSize = 0;
3766 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3767 currentPointerIndex++) {
3768 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3769 lastPointerIndex++) {
3770 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003771 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003772 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003773 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003774 if (currentPointer.toolType == lastPointer.toolType) {
3775 int64_t deltaX = currentPointer.x - lastPointer.x;
3776 int64_t deltaY = currentPointer.y - lastPointer.y;
3777
3778 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3779
3780 // Insert new element into the heap (sift up).
3781 heap[heapSize].currentPointerIndex = currentPointerIndex;
3782 heap[heapSize].lastPointerIndex = lastPointerIndex;
3783 heap[heapSize].distance = distance;
3784 heapSize += 1;
3785 }
3786 }
3787 }
3788
3789 // Heapify
3790 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3791 startIndex -= 1;
3792 for (uint32_t parentIndex = startIndex;;) {
3793 uint32_t childIndex = parentIndex * 2 + 1;
3794 if (childIndex >= heapSize) {
3795 break;
3796 }
3797
3798 if (childIndex + 1 < heapSize &&
3799 heap[childIndex + 1].distance < heap[childIndex].distance) {
3800 childIndex += 1;
3801 }
3802
3803 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3804 break;
3805 }
3806
3807 swap(heap[parentIndex], heap[childIndex]);
3808 parentIndex = childIndex;
3809 }
3810 }
3811
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003812 if (DEBUG_POINTER_ASSIGNMENT) {
3813 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3814 for (size_t i = 0; i < heapSize; i++) {
3815 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3816 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3817 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003818 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003819
3820 // Pull matches out by increasing order of distance.
3821 // To avoid reassigning pointers that have already been matched, the loop keeps track
3822 // of which last and current pointers have been matched using the matchedXXXBits variables.
3823 // It also tracks the used pointer id bits.
3824 BitSet32 matchedLastBits(0);
3825 BitSet32 matchedCurrentBits(0);
3826 BitSet32 usedIdBits(0);
3827 bool first = true;
3828 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3829 while (heapSize > 0) {
3830 if (first) {
3831 // The first time through the loop, we just consume the root element of
3832 // the heap (the one with smallest distance).
3833 first = false;
3834 } else {
3835 // Previous iterations consumed the root element of the heap.
3836 // Pop root element off of the heap (sift down).
3837 heap[0] = heap[heapSize];
3838 for (uint32_t parentIndex = 0;;) {
3839 uint32_t childIndex = parentIndex * 2 + 1;
3840 if (childIndex >= heapSize) {
3841 break;
3842 }
3843
3844 if (childIndex + 1 < heapSize &&
3845 heap[childIndex + 1].distance < heap[childIndex].distance) {
3846 childIndex += 1;
3847 }
3848
3849 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3850 break;
3851 }
3852
3853 swap(heap[parentIndex], heap[childIndex]);
3854 parentIndex = childIndex;
3855 }
3856
Siarhei Vishniakou465e1c02021-12-09 10:47:29 -08003857 if (DEBUG_POINTER_ASSIGNMENT) {
3858 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3859 for (size_t j = 0; j < heapSize; j++) {
3860 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64,
3861 j, heap[j].currentPointerIndex, heap[j].lastPointerIndex,
3862 heap[j].distance);
3863 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003864 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003865 }
3866
3867 heapSize -= 1;
3868
3869 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3870 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3871
3872 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3873 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3874
3875 matchedCurrentBits.markBit(currentPointerIndex);
3876 matchedLastBits.markBit(lastPointerIndex);
3877
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003878 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3879 current.rawPointerData.pointers[currentPointerIndex].id = id;
3880 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3881 current.rawPointerData.markIdBit(id,
3882 current.rawPointerData.isHovering(
3883 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003884 usedIdBits.markBit(id);
3885
Harry Cutts45483602022-08-24 14:36:48 +00003886 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3887 "assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3888 ", distance=%" PRIu64,
3889 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003890 break;
3891 }
3892 }
3893
3894 // Assign fresh ids to pointers that were not matched in the process.
3895 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3896 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3897 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3898
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003899 current.rawPointerData.pointers[currentPointerIndex].id = id;
3900 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3901 current.rawPointerData.markIdBit(id,
3902 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003903
Harry Cutts45483602022-08-24 14:36:48 +00003904 ALOGD_IF(DEBUG_POINTER_ASSIGNMENT,
3905 "assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex,
3906 id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003907 }
3908}
3909
3910int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3911 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3912 return AKEY_STATE_VIRTUAL;
3913 }
3914
3915 for (const VirtualKey& virtualKey : mVirtualKeys) {
3916 if (virtualKey.keyCode == keyCode) {
3917 return AKEY_STATE_UP;
3918 }
3919 }
3920
3921 return AKEY_STATE_UNKNOWN;
3922}
3923
3924int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3925 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3926 return AKEY_STATE_VIRTUAL;
3927 }
3928
3929 for (const VirtualKey& virtualKey : mVirtualKeys) {
3930 if (virtualKey.scanCode == scanCode) {
3931 return AKEY_STATE_UP;
3932 }
3933 }
3934
3935 return AKEY_STATE_UNKNOWN;
3936}
3937
Siarhei Vishniakou74007942022-06-13 13:57:47 -07003938bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask,
3939 const std::vector<int32_t>& keyCodes,
3940 uint8_t* outFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003941 for (const VirtualKey& virtualKey : mVirtualKeys) {
Siarhei Vishniakou74007942022-06-13 13:57:47 -07003942 for (size_t i = 0; i < keyCodes.size(); i++) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003943 if (virtualKey.keyCode == keyCodes[i]) {
3944 outFlags[i] = 1;
3945 }
3946 }
3947 }
3948
3949 return true;
3950}
3951
3952std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3953 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003954 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003955 return std::make_optional(mPointerController->getDisplayId());
3956 } else {
3957 return std::make_optional(mViewport.displayId);
3958 }
3959 }
3960 return std::nullopt;
3961}
3962
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003963} // namespace android