blob: 3fe6fd130f9b5e9bddcc8e25713e7720d56a5e7c [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>
24
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070025#include "CursorButtonAccumulator.h"
26#include "CursorScrollAccumulator.h"
27#include "TouchButtonAccumulator.h"
28#include "TouchCursorInputMapperCommon.h"
29
30namespace android {
31
32// --- Constants ---
33
34// Maximum amount of latency to add to touch events while waiting for data from an
35// external stylus.
36static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
37
38// Maximum amount of time to wait on touch data before pushing out new pressure data.
39static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
40
41// Artificial latency on synthetic events created from stylus data without corresponding touch
42// data.
43static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
44
45// --- Static Definitions ---
46
47template <typename T>
48inline static void swap(T& a, T& b) {
49 T temp = a;
50 a = b;
51 b = temp;
52}
53
54static float calculateCommonVector(float a, float b) {
55 if (a > 0 && b > 0) {
56 return a < b ? a : b;
57 } else if (a < 0 && b < 0) {
58 return a > b ? a : b;
59 } else {
60 return 0;
61 }
62}
63
64inline static float distance(float x1, float y1, float x2, float y2) {
65 return hypotf(x1 - x2, y1 - y2);
66}
67
68inline static int32_t signExtendNybble(int32_t value) {
69 return value >= 8 ? value - 16 : value;
70}
71
72// --- RawPointerAxes ---
73
74RawPointerAxes::RawPointerAxes() {
75 clear();
76}
77
78void RawPointerAxes::clear() {
79 x.clear();
80 y.clear();
81 pressure.clear();
82 touchMajor.clear();
83 touchMinor.clear();
84 toolMajor.clear();
85 toolMinor.clear();
86 orientation.clear();
87 distance.clear();
88 tiltX.clear();
89 tiltY.clear();
90 trackingId.clear();
91 slot.clear();
92}
93
94// --- RawPointerData ---
95
96RawPointerData::RawPointerData() {
97 clear();
98}
99
100void RawPointerData::clear() {
101 pointerCount = 0;
102 clearIdBits();
103}
104
105void RawPointerData::copyFrom(const RawPointerData& other) {
106 pointerCount = other.pointerCount;
107 hoveringIdBits = other.hoveringIdBits;
108 touchingIdBits = other.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +0800109 canceledIdBits = other.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700110
111 for (uint32_t i = 0; i < pointerCount; i++) {
112 pointers[i] = other.pointers[i];
113
114 int id = pointers[i].id;
115 idToIndex[id] = other.idToIndex[id];
116 }
117}
118
119void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
120 float x = 0, y = 0;
121 uint32_t count = touchingIdBits.count();
122 if (count) {
123 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
124 uint32_t id = idBits.clearFirstMarkedBit();
125 const Pointer& pointer = pointerForId(id);
126 x += pointer.x;
127 y += pointer.y;
128 }
129 x /= count;
130 y /= count;
131 }
132 *outX = x;
133 *outY = y;
134}
135
136// --- CookedPointerData ---
137
138CookedPointerData::CookedPointerData() {
139 clear();
140}
141
142void CookedPointerData::clear() {
143 pointerCount = 0;
144 hoveringIdBits.clear();
145 touchingIdBits.clear();
arthurhungcc7f9802020-04-30 17:55:40 +0800146 canceledIdBits.clear();
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000147 validIdBits.clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700148}
149
150void CookedPointerData::copyFrom(const CookedPointerData& other) {
151 pointerCount = other.pointerCount;
152 hoveringIdBits = other.hoveringIdBits;
153 touchingIdBits = other.touchingIdBits;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000154 validIdBits = other.validIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700155
156 for (uint32_t i = 0; i < pointerCount; i++) {
157 pointerProperties[i].copyFrom(other.pointerProperties[i]);
158 pointerCoords[i].copyFrom(other.pointerCoords[i]);
159
160 int id = pointerProperties[i].id;
161 idToIndex[id] = other.idToIndex[id];
162 }
163}
164
165// --- TouchInputMapper ---
166
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800167TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
168 : InputMapper(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700169 mSource(0),
Michael Wright227c5542020-07-02 18:30:52 +0100170 mDeviceMode(DeviceMode::DISABLED),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700171 mDisplayWidth(-1),
172 mDisplayHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700173 mPhysicalWidth(-1),
174 mPhysicalHeight(-1),
175 mPhysicalLeft(0),
176 mPhysicalTop(0),
Prabir Pradhan1728b212021-10-19 16:00:03 -0700177 mInputDeviceOrientation(DISPLAY_ORIENTATION_0) {}
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700178
179TouchInputMapper::~TouchInputMapper() {}
180
181uint32_t TouchInputMapper::getSources() {
182 return mSource;
183}
184
185void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
186 InputMapper::populateDeviceInfo(info);
187
Michael Wright227c5542020-07-02 18:30:52 +0100188 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700189 info->addMotionRange(mOrientedRanges.x);
190 info->addMotionRange(mOrientedRanges.y);
191 info->addMotionRange(mOrientedRanges.pressure);
192
Chris Yef74dc422020-09-02 22:41:50 -0700193 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
Chris Ye8fa17282020-09-15 17:17:34 -0700194 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
195 //
196 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
197 // motion, i.e. the hardware dimensions, as the finger could move completely across the
198 // touchpad in one sample cycle.
Chris Yef74dc422020-09-02 22:41:50 -0700199 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
200 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
201 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat,
202 x.fuzz, x.resolution);
203 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat,
204 y.fuzz, y.resolution);
205 }
206
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700207 if (mOrientedRanges.haveSize) {
208 info->addMotionRange(mOrientedRanges.size);
209 }
210
211 if (mOrientedRanges.haveTouchSize) {
212 info->addMotionRange(mOrientedRanges.touchMajor);
213 info->addMotionRange(mOrientedRanges.touchMinor);
214 }
215
216 if (mOrientedRanges.haveToolSize) {
217 info->addMotionRange(mOrientedRanges.toolMajor);
218 info->addMotionRange(mOrientedRanges.toolMinor);
219 }
220
221 if (mOrientedRanges.haveOrientation) {
222 info->addMotionRange(mOrientedRanges.orientation);
223 }
224
225 if (mOrientedRanges.haveDistance) {
226 info->addMotionRange(mOrientedRanges.distance);
227 }
228
229 if (mOrientedRanges.haveTilt) {
230 info->addMotionRange(mOrientedRanges.tilt);
231 }
232
233 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
234 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
235 0.0f);
236 }
237 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
238 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
239 0.0f);
240 }
Michael Wright227c5542020-07-02 18:30:52 +0100241 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700242 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
243 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
244 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
245 x.fuzz, x.resolution);
246 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
247 y.fuzz, y.resolution);
248 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
249 x.fuzz, x.resolution);
250 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
251 y.fuzz, y.resolution);
252 }
253 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
254 }
255}
256
257void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700258 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800259 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700260 dumpParameters(dump);
261 dumpVirtualKeys(dump);
262 dumpRawPointerAxes(dump);
263 dumpCalibration(dump);
264 dumpAffineTransformation(dump);
Prabir Pradhan1728b212021-10-19 16:00:03 -0700265 dumpDisplay(dump);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700266
267 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700268 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
269 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
270 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
271 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
272 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
273 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
274 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
275 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
276 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
277 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
278 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
279 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
280 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
281 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
282
283 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
284 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
285 mLastRawState.rawPointerData.pointerCount);
286 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
287 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
288 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
289 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
290 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
291 "toolType=%d, isHovering=%s\n",
292 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
293 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
294 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
295 pointer.distance, pointer.toolType, toString(pointer.isHovering));
296 }
297
298 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
299 mLastCookedState.buttonState);
300 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
301 mLastCookedState.cookedPointerData.pointerCount);
302 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
303 const PointerProperties& pointerProperties =
304 mLastCookedState.cookedPointerData.pointerProperties[i];
305 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000306 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
307 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
308 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700309 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
310 "toolType=%d, isHovering=%s\n",
311 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000312 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
313 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700314 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
315 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
316 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
317 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
318 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
319 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
320 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
321 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
322 pointerProperties.toolType,
323 toString(mLastCookedState.cookedPointerData.isHovering(i)));
324 }
325
326 dump += INDENT3 "Stylus Fusion:\n";
327 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
328 toString(mExternalStylusConnected));
329 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
330 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
331 mExternalStylusFusionTimeout);
332 dump += INDENT3 "External Stylus State:\n";
333 dumpStylusState(dump, mExternalStylusState);
334
Michael Wright227c5542020-07-02 18:30:52 +0100335 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700336 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
337 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
338 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
339 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
340 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
341 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
342 }
343}
344
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700345void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
346 uint32_t changes) {
347 InputMapper::configure(when, config, changes);
348
349 mConfig = *config;
350
351 if (!changes) { // first time only
352 // Configure basic parameters.
353 configureParameters();
354
355 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800356 mCursorScrollAccumulator.configure(getDeviceContext());
357 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700358
359 // Configure absolute axis information.
360 configureRawPointerAxes();
361
362 // Prepare input device calibration.
363 parseCalibration();
364 resolveCalibration();
365 }
366
367 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
368 // Update location calibration to reflect current settings
369 updateAffineTransformation();
370 }
371
372 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
373 // Update pointer speed.
374 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
375 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
376 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
377 }
378
379 bool resetNeeded = false;
380 if (!changes ||
381 (changes &
382 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800383 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700384 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
385 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
386 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700387 // Configure device sources, display dimensions, orientation and
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700388 // scaling factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700389 configureInputDevice(when, &resetNeeded);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700390 }
391
392 if (changes && resetNeeded) {
393 // Send reset, unless this is the first time the device has been configured,
394 // in which case the reader will call reset itself after all mappers are ready.
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +0000395 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700396 getListener().notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700397 }
398}
399
400void TouchInputMapper::resolveExternalStylusPresence() {
401 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800402 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700403 mExternalStylusConnected = !devices.empty();
404
405 if (!mExternalStylusConnected) {
406 resetExternalStylus();
407 }
408}
409
410void TouchInputMapper::configureParameters() {
411 // Use the pointer presentation mode for devices that do not support distinct
412 // multitouch. The spot-based presentation relies on being able to accurately
413 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800414 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100415 ? Parameters::GestureMode::SINGLE_TOUCH
416 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700417
418 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800419 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
420 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700421 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100422 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700423 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100424 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700425 } else if (gestureModeString != "default") {
426 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
427 }
428 }
429
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800430 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700431 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100432 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800433 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700434 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100435 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800436 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
437 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700438 // The device is a cursor device with a touch pad attached.
439 // By default don't use the touch pad to move the pointer.
Michael Wright227c5542020-07-02 18:30:52 +0100440 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700441 } else {
442 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100443 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700444 }
445
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800446 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700447
448 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800449 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
450 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700451 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100452 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700453 } else if (deviceTypeString == "touchPad") {
Michael Wright227c5542020-07-02 18:30:52 +0100454 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700455 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100456 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700457 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100458 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700459 } else if (deviceTypeString != "default") {
460 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
461 }
462 }
463
Michael Wright227c5542020-07-02 18:30:52 +0100464 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800465 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
466 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700467
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700468 mParameters.orientation = Parameters::Orientation::ORIENTATION_0;
469 String8 orientationString;
470 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientation"),
471 orientationString)) {
472 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
473 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
474 } else if (orientationString == "ORIENTATION_90") {
475 mParameters.orientation = Parameters::Orientation::ORIENTATION_90;
476 } else if (orientationString == "ORIENTATION_180") {
477 mParameters.orientation = Parameters::Orientation::ORIENTATION_180;
478 } else if (orientationString == "ORIENTATION_270") {
479 mParameters.orientation = Parameters::Orientation::ORIENTATION_270;
480 } else if (orientationString != "ORIENTATION_0") {
481 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.string());
482 }
483 }
484
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700485 mParameters.hasAssociatedDisplay = false;
486 mParameters.associatedDisplayIsExternal = false;
487 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100488 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
489 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700490 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100491 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800492 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700493 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800494 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
495 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700496 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
497 }
498 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800499 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700500 mParameters.hasAssociatedDisplay = true;
501 }
502
503 // Initial downs on external touch devices should wake the device.
504 // Normally we don't do this for internal touch screens to prevent them from waking
505 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800506 mParameters.wake = getDeviceContext().isExternal();
507 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700508}
509
510void TouchInputMapper::dumpParameters(std::string& dump) {
511 dump += INDENT3 "Parameters:\n";
512
Dominik Laskowski75788452021-02-09 18:51:25 -0800513 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700514
Dominik Laskowski75788452021-02-09 18:51:25 -0800515 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700516
517 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
518 "displayId='%s'\n",
519 toString(mParameters.hasAssociatedDisplay),
520 toString(mParameters.associatedDisplayIsExternal),
521 mParameters.uniqueDisplayId.c_str());
522 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800523 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700524}
525
526void TouchInputMapper::configureRawPointerAxes() {
527 mRawPointerAxes.clear();
528}
529
530void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
531 dump += INDENT3 "Raw Touch Axes:\n";
532 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
533 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
534 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
535 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
536 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
537 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
538 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
539 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
540 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
541 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
542 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
543 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
544 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
545}
546
547bool TouchInputMapper::hasExternalStylus() const {
548 return mExternalStylusConnected;
549}
550
551/**
552 * Determine which DisplayViewport to use.
553 * 1. If display port is specified, return the matching viewport. If matching viewport not
554 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800555 * 2. Always use the suggested viewport from WindowManagerService for pointers.
556 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700557 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800558 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700559 */
560std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800561 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800562 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700563 if (displayPort) {
564 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800565 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700566 }
567
Michael Wright227c5542020-07-02 18:30:52 +0100568 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800569 std::optional<DisplayViewport> viewport =
570 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
571 if (viewport) {
572 return viewport;
573 } else {
574 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
575 mConfig.defaultPointerDisplayId);
576 }
577 }
578
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700579 // Check if uniqueDisplayId is specified in idc file.
580 if (!mParameters.uniqueDisplayId.empty()) {
581 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
582 }
583
584 ViewportType viewportTypeToUse;
585 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100586 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700587 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100588 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700589 }
590
591 std::optional<DisplayViewport> viewport =
592 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100593 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700594 ALOGW("Input device %s should be associated with external display, "
595 "fallback to internal one for the external viewport is not found.",
596 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100597 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700598 }
599
600 return viewport;
601 }
602
603 // No associated display, return a non-display viewport.
604 DisplayViewport newViewport;
605 // Raw width and height in the natural orientation.
606 int32_t rawWidth = mRawPointerAxes.getRawWidth();
607 int32_t rawHeight = mRawPointerAxes.getRawHeight();
608 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
609 return std::make_optional(newViewport);
610}
611
Prabir Pradhan1728b212021-10-19 16:00:03 -0700612void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100613 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700614
615 resolveExternalStylusPresence();
616
617 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100618 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000619 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700620 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100621 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700622 if (hasStylus()) {
623 mSource |= AINPUT_SOURCE_STYLUS;
624 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800625 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700626 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100627 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700628 if (hasStylus()) {
629 mSource |= AINPUT_SOURCE_STYLUS;
630 }
631 if (hasExternalStylus()) {
632 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
633 }
Michael Wright227c5542020-07-02 18:30:52 +0100634 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700635 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100636 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700637 } else {
638 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100639 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700640 }
641
642 // Ensure we have valid X and Y axes.
643 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
644 ALOGW("Touch device '%s' did not report support for X or Y axis! "
645 "The device will be inoperable.",
646 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100647 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700648 return;
649 }
650
651 // Get associated display dimensions.
652 std::optional<DisplayViewport> newViewport = findViewport();
653 if (!newViewport) {
654 ALOGI("Touch device '%s' could not query the properties of its associated "
655 "display. The device will be inoperable until the display size "
656 "becomes available.",
657 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100658 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700659 return;
660 }
661
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000662 if (!newViewport->isActive) {
663 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
664 getDeviceName().c_str(), getDeviceId());
665 mDeviceMode = DeviceMode::DISABLED;
666 return;
667 }
668
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700669 // Raw width and height in the natural orientation.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700670 const int32_t rawWidth = mRawPointerAxes.getRawWidth();
671 const int32_t rawHeight = mRawPointerAxes.getRawHeight();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700672
Prabir Pradhan1728b212021-10-19 16:00:03 -0700673 const bool viewportChanged = mViewport != *newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700674 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700675 if (viewportChanged) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700676 const bool viewportOrientationChanged = mViewport.orientation != newViewport->orientation;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700677 mViewport = *newViewport;
678
Michael Wright227c5542020-07-02 18:30:52 +0100679 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhan1728b212021-10-19 16:00:03 -0700680 // Convert rotated viewport to the natural orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700681 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
682 int32_t naturalPhysicalLeft, naturalPhysicalTop;
683 int32_t naturalDeviceWidth, naturalDeviceHeight;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700684
Prabir Pradhan1728b212021-10-19 16:00:03 -0700685 // Apply the inverse of the input device orientation so that the input device is
686 // configured in the same orientation as the viewport. The input device orientation will
687 // be re-applied by mInputDeviceOrientation.
688 const int32_t naturalDeviceOrientation =
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700689 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
Prabir Pradhan1728b212021-10-19 16:00:03 -0700690 switch (naturalDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700691 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700692 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
693 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800694 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700695 naturalPhysicalTop = mViewport.physicalLeft;
696 naturalDeviceWidth = mViewport.deviceHeight;
697 naturalDeviceHeight = mViewport.deviceWidth;
698 break;
699 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700700 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
701 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
702 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
703 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
704 naturalDeviceWidth = mViewport.deviceWidth;
705 naturalDeviceHeight = mViewport.deviceHeight;
706 break;
707 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700708 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
709 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
710 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800711 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700712 naturalDeviceWidth = mViewport.deviceHeight;
713 naturalDeviceHeight = mViewport.deviceWidth;
714 break;
715 case DISPLAY_ORIENTATION_0:
716 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700717 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
718 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
719 naturalPhysicalLeft = mViewport.physicalLeft;
720 naturalPhysicalTop = mViewport.physicalTop;
721 naturalDeviceWidth = mViewport.deviceWidth;
722 naturalDeviceHeight = mViewport.deviceHeight;
723 break;
724 }
725
726 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
727 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
728 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
729 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
730 }
731
732 mPhysicalWidth = naturalPhysicalWidth;
733 mPhysicalHeight = naturalPhysicalHeight;
734 mPhysicalLeft = naturalPhysicalLeft;
735 mPhysicalTop = naturalPhysicalTop;
736
Prabir Pradhan1728b212021-10-19 16:00:03 -0700737 const int32_t oldDisplayWidth = mDisplayWidth;
738 const int32_t oldDisplayHeight = mDisplayHeight;
739 mDisplayWidth = naturalDeviceWidth;
740 mDisplayHeight = naturalDeviceHeight;
Prabir Pradhan5632d622021-09-06 07:57:20 -0700741
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000742 // InputReader works in the un-rotated display coordinate space, so we don't need to do
743 // anything if the device is already orientation-aware. If the device is not
744 // orientation-aware, then we need to apply the inverse rotation of the display so that
745 // when the display rotation is applied later as a part of the per-window transform, we
746 // get the expected screen coordinates.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700747 mInputDeviceOrientation = mParameters.orientationAware
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +0000748 ? DISPLAY_ORIENTATION_0
749 : getInverseRotation(mViewport.orientation);
750 // For orientation-aware devices that work in the un-rotated coordinate space, the
751 // viewport update should be skipped if it is only a change in the orientation.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700752 skipViewportUpdate = mParameters.orientationAware && mDisplayWidth == oldDisplayWidth &&
753 mDisplayHeight == oldDisplayHeight && viewportOrientationChanged;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700754
755 // Apply the input device orientation for the device.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700756 mInputDeviceOrientation =
757 (mInputDeviceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700758 } else {
759 mPhysicalWidth = rawWidth;
760 mPhysicalHeight = rawHeight;
761 mPhysicalLeft = 0;
762 mPhysicalTop = 0;
763
Prabir Pradhan1728b212021-10-19 16:00:03 -0700764 mDisplayWidth = rawWidth;
765 mDisplayHeight = rawHeight;
766 mInputDeviceOrientation = DISPLAY_ORIENTATION_0;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700767 }
768 }
769
770 // If moving between pointer modes, need to reset some state.
771 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
772 if (deviceModeChanged) {
773 mOrientedRanges.clear();
774 }
775
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800776 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
777 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100778 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800779 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000780 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
781 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800782 if (mPointerController == nullptr) {
783 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700784 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000785 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800786 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
787 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700788 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100789 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700790 }
791
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700792 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700793 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
794 "display id %d",
Prabir Pradhan1728b212021-10-19 16:00:03 -0700795 getDeviceId(), getDeviceName().c_str(), mDisplayWidth, mDisplayHeight,
796 mInputDeviceOrientation, mDeviceMode, mViewport.displayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700797
798 // Configure X and Y factors.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700799 mXScale = float(mDisplayWidth) / rawWidth;
800 mYScale = float(mDisplayHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700801 mXPrecision = 1.0f / mXScale;
802 mYPrecision = 1.0f / mYScale;
803
804 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
805 mOrientedRanges.x.source = mSource;
806 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
807 mOrientedRanges.y.source = mSource;
808
809 configureVirtualKeys();
810
811 // Scale factor for terms that are not oriented in a particular axis.
812 // If the pixels are square then xScale == yScale otherwise we fake it
813 // by choosing an average.
814 mGeometricScale = avg(mXScale, mYScale);
815
816 // Size of diagonal axis.
Prabir Pradhan1728b212021-10-19 16:00:03 -0700817 float diagonalSize = hypotf(mDisplayWidth, mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700818
819 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100820 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700821 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
822 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
823 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
824 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
825 } else {
826 mSizeScale = 0.0f;
827 }
828
829 mOrientedRanges.haveTouchSize = true;
830 mOrientedRanges.haveToolSize = true;
831 mOrientedRanges.haveSize = true;
832
833 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
834 mOrientedRanges.touchMajor.source = mSource;
835 mOrientedRanges.touchMajor.min = 0;
836 mOrientedRanges.touchMajor.max = diagonalSize;
837 mOrientedRanges.touchMajor.flat = 0;
838 mOrientedRanges.touchMajor.fuzz = 0;
839 mOrientedRanges.touchMajor.resolution = 0;
840
841 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
842 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
843
844 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
845 mOrientedRanges.toolMajor.source = mSource;
846 mOrientedRanges.toolMajor.min = 0;
847 mOrientedRanges.toolMajor.max = diagonalSize;
848 mOrientedRanges.toolMajor.flat = 0;
849 mOrientedRanges.toolMajor.fuzz = 0;
850 mOrientedRanges.toolMajor.resolution = 0;
851
852 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
853 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
854
855 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
856 mOrientedRanges.size.source = mSource;
857 mOrientedRanges.size.min = 0;
858 mOrientedRanges.size.max = 1.0;
859 mOrientedRanges.size.flat = 0;
860 mOrientedRanges.size.fuzz = 0;
861 mOrientedRanges.size.resolution = 0;
862 } else {
863 mSizeScale = 0.0f;
864 }
865
866 // Pressure factors.
867 mPressureScale = 0;
868 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100869 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
870 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700871 if (mCalibration.havePressureScale) {
872 mPressureScale = mCalibration.pressureScale;
873 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
874 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
875 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
876 }
877 }
878
879 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
880 mOrientedRanges.pressure.source = mSource;
881 mOrientedRanges.pressure.min = 0;
882 mOrientedRanges.pressure.max = pressureMax;
883 mOrientedRanges.pressure.flat = 0;
884 mOrientedRanges.pressure.fuzz = 0;
885 mOrientedRanges.pressure.resolution = 0;
886
887 // Tilt
888 mTiltXCenter = 0;
889 mTiltXScale = 0;
890 mTiltYCenter = 0;
891 mTiltYScale = 0;
892 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
893 if (mHaveTilt) {
894 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
895 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
896 mTiltXScale = M_PI / 180;
897 mTiltYScale = M_PI / 180;
898
Tatsunosuke Tobita35e05532021-06-30 14:49:32 +0900899 if (mRawPointerAxes.tiltX.resolution) {
900 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
901 }
902 if (mRawPointerAxes.tiltY.resolution) {
903 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
904 }
905
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700906 mOrientedRanges.haveTilt = true;
907
908 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
909 mOrientedRanges.tilt.source = mSource;
910 mOrientedRanges.tilt.min = 0;
911 mOrientedRanges.tilt.max = M_PI_2;
912 mOrientedRanges.tilt.flat = 0;
913 mOrientedRanges.tilt.fuzz = 0;
914 mOrientedRanges.tilt.resolution = 0;
915 }
916
917 // Orientation
918 mOrientationScale = 0;
919 if (mHaveTilt) {
920 mOrientedRanges.haveOrientation = true;
921
922 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
923 mOrientedRanges.orientation.source = mSource;
924 mOrientedRanges.orientation.min = -M_PI;
925 mOrientedRanges.orientation.max = M_PI;
926 mOrientedRanges.orientation.flat = 0;
927 mOrientedRanges.orientation.fuzz = 0;
928 mOrientedRanges.orientation.resolution = 0;
929 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100930 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700931 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100932 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700933 if (mRawPointerAxes.orientation.valid) {
934 if (mRawPointerAxes.orientation.maxValue > 0) {
935 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
936 } else if (mRawPointerAxes.orientation.minValue < 0) {
937 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
938 } else {
939 mOrientationScale = 0;
940 }
941 }
942 }
943
944 mOrientedRanges.haveOrientation = true;
945
946 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
947 mOrientedRanges.orientation.source = mSource;
948 mOrientedRanges.orientation.min = -M_PI_2;
949 mOrientedRanges.orientation.max = M_PI_2;
950 mOrientedRanges.orientation.flat = 0;
951 mOrientedRanges.orientation.fuzz = 0;
952 mOrientedRanges.orientation.resolution = 0;
953 }
954
955 // Distance
956 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100957 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
958 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700959 if (mCalibration.haveDistanceScale) {
960 mDistanceScale = mCalibration.distanceScale;
961 } else {
962 mDistanceScale = 1.0f;
963 }
964 }
965
966 mOrientedRanges.haveDistance = true;
967
968 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
969 mOrientedRanges.distance.source = mSource;
970 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
971 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
972 mOrientedRanges.distance.flat = 0;
973 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
974 mOrientedRanges.distance.resolution = 0;
975 }
976
977 // Compute oriented precision, scales and ranges.
978 // Note that the maximum value reported is an inclusive maximum value so it is one
Prabir Pradhan1728b212021-10-19 16:00:03 -0700979 // unit less than the total width or height of the display.
980 switch (mInputDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700981 case DISPLAY_ORIENTATION_90:
982 case DISPLAY_ORIENTATION_270:
983 mOrientedXPrecision = mYPrecision;
984 mOrientedYPrecision = mXPrecision;
985
Prabir Pradhan1728b212021-10-19 16:00:03 -0700986 mOrientedRanges.x.min = 0;
987 mOrientedRanges.x.max = mDisplayHeight - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700988 mOrientedRanges.x.flat = 0;
989 mOrientedRanges.x.fuzz = 0;
990 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
991
Prabir Pradhan1728b212021-10-19 16:00:03 -0700992 mOrientedRanges.y.min = 0;
993 mOrientedRanges.y.max = mDisplayWidth - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700994 mOrientedRanges.y.flat = 0;
995 mOrientedRanges.y.fuzz = 0;
996 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
997 break;
998
999 default:
1000 mOrientedXPrecision = mXPrecision;
1001 mOrientedYPrecision = mYPrecision;
1002
Prabir Pradhan1728b212021-10-19 16:00:03 -07001003 mOrientedRanges.x.min = 0;
1004 mOrientedRanges.x.max = mDisplayWidth - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001005 mOrientedRanges.x.flat = 0;
1006 mOrientedRanges.x.fuzz = 0;
1007 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1008
Prabir Pradhan1728b212021-10-19 16:00:03 -07001009 mOrientedRanges.y.min = 0;
1010 mOrientedRanges.y.max = mDisplayHeight - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001011 mOrientedRanges.y.flat = 0;
1012 mOrientedRanges.y.fuzz = 0;
1013 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1014 break;
1015 }
1016
1017 // Location
1018 updateAffineTransformation();
1019
Michael Wright227c5542020-07-02 18:30:52 +01001020 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001021 // Compute pointer gesture detection parameters.
1022 float rawDiagonal = hypotf(rawWidth, rawHeight);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001023 float displayDiagonal = hypotf(mDisplayWidth, mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001024
1025 // Scale movements such that one whole swipe of the touch pad covers a
1026 // given area relative to the diagonal size of the display when no acceleration
1027 // is applied.
1028 // Assume that the touch pad has a square aspect ratio such that movements in
1029 // X and Y of the same number of raw units cover the same physical distance.
1030 mPointerXMovementScale =
1031 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1032 mPointerYMovementScale = mPointerXMovementScale;
1033
1034 // Scale zooms to cover a smaller range of the display than movements do.
1035 // This value determines the area around the pointer that is affected by freeform
1036 // pointer gestures.
1037 mPointerXZoomScale =
1038 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1039 mPointerYZoomScale = mPointerXZoomScale;
1040
1041 // Max width between pointers to detect a swipe gesture is more than some fraction
1042 // of the diagonal axis of the touch pad. Touches that are wider than this are
1043 // translated into freeform gestures.
1044 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1045
1046 // Abort current pointer usages because the state has changed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001047 const nsecs_t readTime = when; // synthetic event
1048 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001049 }
1050
1051 // Inform the dispatcher about the changes.
1052 *outResetNeeded = true;
1053 bumpGeneration();
1054 }
1055}
1056
Prabir Pradhan1728b212021-10-19 16:00:03 -07001057void TouchInputMapper::dumpDisplay(std::string& dump) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001058 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Prabir Pradhan1728b212021-10-19 16:00:03 -07001059 dump += StringPrintf(INDENT3 "DisplayWidth: %dpx\n", mDisplayWidth);
1060 dump += StringPrintf(INDENT3 "DisplayHeight: %dpx\n", mDisplayHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001061 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1062 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1063 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1064 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001065 dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001066}
1067
1068void TouchInputMapper::configureVirtualKeys() {
1069 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001070 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001071
1072 mVirtualKeys.clear();
1073
1074 if (virtualKeyDefinitions.size() == 0) {
1075 return;
1076 }
1077
1078 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1079 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1080 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1081 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1082
1083 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1084 VirtualKey virtualKey;
1085
1086 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1087 int32_t keyCode;
1088 int32_t dummyKeyMetaState;
1089 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001090 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1091 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001092 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1093 continue; // drop the key
1094 }
1095
1096 virtualKey.keyCode = keyCode;
1097 virtualKey.flags = flags;
1098
1099 // convert the key definition's display coordinates into touch coordinates for a hit box
1100 int32_t halfWidth = virtualKeyDefinition.width / 2;
1101 int32_t halfHeight = virtualKeyDefinition.height / 2;
1102
1103 virtualKey.hitLeft =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001104 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001105 touchScreenLeft;
1106 virtualKey.hitRight =
Prabir Pradhan1728b212021-10-19 16:00:03 -07001107 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mDisplayWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001108 touchScreenLeft;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001109 virtualKey.hitTop =
1110 (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001111 touchScreenTop;
Prabir Pradhan1728b212021-10-19 16:00:03 -07001112 virtualKey.hitBottom =
1113 (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight / mDisplayHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001114 touchScreenTop;
1115 mVirtualKeys.push_back(virtualKey);
1116 }
1117}
1118
1119void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1120 if (!mVirtualKeys.empty()) {
1121 dump += INDENT3 "Virtual Keys:\n";
1122
1123 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1124 const VirtualKey& virtualKey = mVirtualKeys[i];
1125 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1126 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1127 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1128 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1129 }
1130 }
1131}
1132
1133void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001134 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001135 Calibration& out = mCalibration;
1136
1137 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001138 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139 String8 sizeCalibrationString;
1140 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1141 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001142 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001143 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001144 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001146 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001148 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001149 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001150 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001151 } else if (sizeCalibrationString != "default") {
1152 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1153 }
1154 }
1155
1156 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1157 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1158 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1159
1160 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001161 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001162 String8 pressureCalibrationString;
1163 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1164 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001165 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001166 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001167 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001168 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001169 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001170 } else if (pressureCalibrationString != "default") {
1171 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1172 pressureCalibrationString.string());
1173 }
1174 }
1175
1176 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1177
1178 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001179 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001180 String8 orientationCalibrationString;
1181 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1182 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001183 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001184 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001185 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001186 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001187 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001188 } else if (orientationCalibrationString != "default") {
1189 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1190 orientationCalibrationString.string());
1191 }
1192 }
1193
1194 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001195 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001196 String8 distanceCalibrationString;
1197 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1198 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001199 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001200 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001201 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001202 } else if (distanceCalibrationString != "default") {
1203 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1204 distanceCalibrationString.string());
1205 }
1206 }
1207
1208 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1209
Michael Wright227c5542020-07-02 18:30:52 +01001210 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211 String8 coverageCalibrationString;
1212 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1213 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001214 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001215 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001216 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001217 } else if (coverageCalibrationString != "default") {
1218 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1219 coverageCalibrationString.string());
1220 }
1221 }
1222}
1223
1224void TouchInputMapper::resolveCalibration() {
1225 // Size
1226 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001227 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1228 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229 }
1230 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001231 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001232 }
1233
1234 // Pressure
1235 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001236 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1237 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001238 }
1239 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001240 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001241 }
1242
1243 // Orientation
1244 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001245 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1246 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001247 }
1248 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001249 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001250 }
1251
1252 // Distance
1253 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001254 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1255 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001256 }
1257 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001258 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001259 }
1260
1261 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001262 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1263 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001264 }
1265}
1266
1267void TouchInputMapper::dumpCalibration(std::string& dump) {
1268 dump += INDENT3 "Calibration:\n";
1269
1270 // Size
1271 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001272 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001273 dump += INDENT4 "touch.size.calibration: none\n";
1274 break;
Michael Wright227c5542020-07-02 18:30:52 +01001275 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001276 dump += INDENT4 "touch.size.calibration: geometric\n";
1277 break;
Michael Wright227c5542020-07-02 18:30:52 +01001278 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001279 dump += INDENT4 "touch.size.calibration: diameter\n";
1280 break;
Michael Wright227c5542020-07-02 18:30:52 +01001281 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001282 dump += INDENT4 "touch.size.calibration: box\n";
1283 break;
Michael Wright227c5542020-07-02 18:30:52 +01001284 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001285 dump += INDENT4 "touch.size.calibration: area\n";
1286 break;
1287 default:
1288 ALOG_ASSERT(false);
1289 }
1290
1291 if (mCalibration.haveSizeScale) {
1292 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1293 }
1294
1295 if (mCalibration.haveSizeBias) {
1296 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1297 }
1298
1299 if (mCalibration.haveSizeIsSummed) {
1300 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1301 toString(mCalibration.sizeIsSummed));
1302 }
1303
1304 // Pressure
1305 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001306 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 dump += INDENT4 "touch.pressure.calibration: none\n";
1308 break;
Michael Wright227c5542020-07-02 18:30:52 +01001309 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001310 dump += INDENT4 "touch.pressure.calibration: physical\n";
1311 break;
Michael Wright227c5542020-07-02 18:30:52 +01001312 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001313 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1314 break;
1315 default:
1316 ALOG_ASSERT(false);
1317 }
1318
1319 if (mCalibration.havePressureScale) {
1320 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1321 }
1322
1323 // Orientation
1324 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001325 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001326 dump += INDENT4 "touch.orientation.calibration: none\n";
1327 break;
Michael Wright227c5542020-07-02 18:30:52 +01001328 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001329 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1330 break;
Michael Wright227c5542020-07-02 18:30:52 +01001331 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001332 dump += INDENT4 "touch.orientation.calibration: vector\n";
1333 break;
1334 default:
1335 ALOG_ASSERT(false);
1336 }
1337
1338 // Distance
1339 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001340 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001341 dump += INDENT4 "touch.distance.calibration: none\n";
1342 break;
Michael Wright227c5542020-07-02 18:30:52 +01001343 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001344 dump += INDENT4 "touch.distance.calibration: scaled\n";
1345 break;
1346 default:
1347 ALOG_ASSERT(false);
1348 }
1349
1350 if (mCalibration.haveDistanceScale) {
1351 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1352 }
1353
1354 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001355 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001356 dump += INDENT4 "touch.coverage.calibration: none\n";
1357 break;
Michael Wright227c5542020-07-02 18:30:52 +01001358 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001359 dump += INDENT4 "touch.coverage.calibration: box\n";
1360 break;
1361 default:
1362 ALOG_ASSERT(false);
1363 }
1364}
1365
1366void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1367 dump += INDENT3 "Affine Transformation:\n";
1368
1369 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1370 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1371 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1372 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1373 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1374 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1375}
1376
1377void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001378 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07001379 mInputDeviceOrientation);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001380}
1381
1382void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001383 mCursorButtonAccumulator.reset(getDeviceContext());
1384 mCursorScrollAccumulator.reset(getDeviceContext());
1385 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001386
1387 mPointerVelocityControl.reset();
1388 mWheelXVelocityControl.reset();
1389 mWheelYVelocityControl.reset();
1390
1391 mRawStatesPending.clear();
1392 mCurrentRawState.clear();
1393 mCurrentCookedState.clear();
1394 mLastRawState.clear();
1395 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001396 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001397 mSentHoverEnter = false;
1398 mHavePointerIds = false;
1399 mCurrentMotionAborted = false;
1400 mDownTime = 0;
1401
1402 mCurrentVirtualKey.down = false;
1403
1404 mPointerGesture.reset();
1405 mPointerSimple.reset();
1406 resetExternalStylus();
1407
1408 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001409 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001410 mPointerController->clearSpots();
1411 }
1412
1413 InputMapper::reset(when);
1414}
1415
1416void TouchInputMapper::resetExternalStylus() {
1417 mExternalStylusState.clear();
1418 mExternalStylusId = -1;
1419 mExternalStylusFusionTimeout = LLONG_MAX;
1420 mExternalStylusDataPending = false;
1421}
1422
1423void TouchInputMapper::clearStylusDataPendingFlags() {
1424 mExternalStylusDataPending = false;
1425 mExternalStylusFusionTimeout = LLONG_MAX;
1426}
1427
1428void TouchInputMapper::process(const RawEvent* rawEvent) {
1429 mCursorButtonAccumulator.process(rawEvent);
1430 mCursorScrollAccumulator.process(rawEvent);
1431 mTouchButtonAccumulator.process(rawEvent);
1432
1433 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001434 sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001435 }
1436}
1437
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001438void TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001439 // Push a new state.
1440 mRawStatesPending.emplace_back();
1441
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001442 RawState& next = mRawStatesPending.back();
1443 next.clear();
1444 next.when = when;
1445 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001446
1447 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001448 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001449 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1450
1451 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001452 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1453 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001454 mCursorScrollAccumulator.finishSync();
1455
1456 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001457 syncTouch(when, &next);
1458
1459 // The last RawState is the actually second to last, since we just added a new state
1460 const RawState& last =
1461 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001462
1463 // Assign pointer ids.
1464 if (!mHavePointerIds) {
1465 assignPointerIds(last, next);
1466 }
1467
1468#if DEBUG_RAW_EVENTS
1469 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001470 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001471 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1472 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1473 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1474 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001475#endif
1476
Arthur Hung9ad18942021-06-19 02:04:46 +00001477 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1478 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1479 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1480 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1481 next.rawPointerData.hoveringIdBits.value);
1482 }
1483
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001484 processRawTouches(false /*timeout*/);
1485}
1486
1487void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001488 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001489 // Drop all input if the device is disabled.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001490 cancelTouch(mCurrentRawState.when, mCurrentRawState.readTime);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001491 mCurrentCookedState.clear();
1492 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001493 return;
1494 }
1495
1496 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1497 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1498 // touching the current state will only observe the events that have been dispatched to the
1499 // rest of the pipeline.
1500 const size_t N = mRawStatesPending.size();
1501 size_t count;
1502 for (count = 0; count < N; count++) {
1503 const RawState& next = mRawStatesPending[count];
1504
1505 // A failure to assign the stylus id means that we're waiting on stylus data
1506 // and so should defer the rest of the pipeline.
1507 if (assignExternalStylusId(next, timeout)) {
1508 break;
1509 }
1510
1511 // All ready to go.
1512 clearStylusDataPendingFlags();
1513 mCurrentRawState.copyFrom(next);
1514 if (mCurrentRawState.when < mLastRawState.when) {
1515 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001516 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001517 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001518 cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001519 }
1520 if (count != 0) {
1521 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1522 }
1523
1524 if (mExternalStylusDataPending) {
1525 if (timeout) {
1526 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1527 clearStylusDataPendingFlags();
1528 mCurrentRawState.copyFrom(mLastRawState);
1529#if DEBUG_STYLUS_FUSION
1530 ALOGD("Timeout expired, synthesizing event with new stylus data");
1531#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001532 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
1533 cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001534 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1535 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1536 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1537 }
1538 }
1539}
1540
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001541void TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001542 // Always start with a clean state.
1543 mCurrentCookedState.clear();
1544
1545 // Apply stylus buttons to current raw state.
1546 applyExternalStylusButtonState(when);
1547
1548 // Handle policy on initial down or hover events.
1549 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1550 mCurrentRawState.rawPointerData.pointerCount != 0;
1551
1552 uint32_t policyFlags = 0;
1553 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1554 if (initialDown || buttonsPressed) {
1555 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001556 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001557 getContext()->fadePointer();
1558 }
1559
1560 if (mParameters.wake) {
1561 policyFlags |= POLICY_FLAG_WAKE;
1562 }
1563 }
1564
1565 // Consume raw off-screen touches before cooking pointer data.
1566 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001567 if (consumeRawTouches(when, readTime, policyFlags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001568 mCurrentRawState.rawPointerData.clear();
1569 }
1570
1571 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1572 // with cooked pointer data that has the same ids and indices as the raw data.
1573 // The following code can use either the raw or cooked data, as needed.
1574 cookPointerData();
1575
1576 // Apply stylus pressure to current cooked state.
1577 applyExternalStylusTouchState(when);
1578
1579 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001580 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1581 mSource, mViewport.displayId, policyFlags, mLastCookedState.buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001582 mCurrentCookedState.buttonState);
1583
1584 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001585 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001586 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1587 uint32_t id = idBits.clearFirstMarkedBit();
1588 const RawPointerData::Pointer& pointer =
1589 mCurrentRawState.rawPointerData.pointerForId(id);
1590 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1591 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1592 mCurrentCookedState.stylusIdBits.markBit(id);
1593 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1594 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1595 mCurrentCookedState.fingerIdBits.markBit(id);
1596 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1597 mCurrentCookedState.mouseIdBits.markBit(id);
1598 }
1599 }
1600 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1601 uint32_t id = idBits.clearFirstMarkedBit();
1602 const RawPointerData::Pointer& pointer =
1603 mCurrentRawState.rawPointerData.pointerForId(id);
1604 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1605 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1606 mCurrentCookedState.stylusIdBits.markBit(id);
1607 }
1608 }
1609
1610 // Stylus takes precedence over all tools, then mouse, then finger.
1611 PointerUsage pointerUsage = mPointerUsage;
1612 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1613 mCurrentCookedState.mouseIdBits.clear();
1614 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001615 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001616 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1617 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001618 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001619 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1620 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001621 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001622 }
1623
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001624 dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001625 } else {
Garfield Tanc734e4f2021-01-15 20:01:39 -08001626 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001627
1628 if (!mCurrentMotionAborted) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001629 dispatchButtonRelease(when, readTime, policyFlags);
1630 dispatchHoverExit(when, readTime, policyFlags);
1631 dispatchTouches(when, readTime, policyFlags);
1632 dispatchHoverEnterAndMove(when, readTime, policyFlags);
1633 dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001634 }
1635
1636 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1637 mCurrentMotionAborted = false;
1638 }
1639 }
1640
1641 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001642 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001643 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1644 mCurrentCookedState.buttonState);
1645
1646 // Clear some transient state.
1647 mCurrentRawState.rawVScroll = 0;
1648 mCurrentRawState.rawHScroll = 0;
1649
1650 // Copy current touch to last touch in preparation for the next cycle.
1651 mLastRawState.copyFrom(mCurrentRawState);
1652 mLastCookedState.copyFrom(mCurrentCookedState);
1653}
1654
Garfield Tanc734e4f2021-01-15 20:01:39 -08001655void TouchInputMapper::updateTouchSpots() {
1656 if (!mConfig.showTouches || mPointerController == nullptr) {
1657 return;
1658 }
1659
1660 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1661 // clear touch spots.
1662 if (mDeviceMode != DeviceMode::DIRECT &&
1663 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1664 return;
1665 }
1666
1667 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1668 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1669
1670 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand7482e72021-03-09 13:54:55 -08001671 setTouchSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1672 mCurrentCookedState.cookedPointerData.idToIndex,
1673 mCurrentCookedState.cookedPointerData.touchingIdBits, mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001674}
1675
1676bool TouchInputMapper::isTouchScreen() {
1677 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1678 mParameters.hasAssociatedDisplay;
1679}
1680
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001681void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001682 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001683 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1684 }
1685}
1686
1687void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1688 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1689 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1690
1691 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1692 float pressure = mExternalStylusState.pressure;
1693 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1694 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1695 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1696 }
1697 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1698 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1699
1700 PointerProperties& properties =
1701 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1702 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1703 properties.toolType = mExternalStylusState.toolType;
1704 }
1705 }
1706}
1707
1708bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001709 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001710 return false;
1711 }
1712
1713 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1714 state.rawPointerData.pointerCount != 0;
1715 if (initialDown) {
1716 if (mExternalStylusState.pressure != 0.0f) {
1717#if DEBUG_STYLUS_FUSION
1718 ALOGD("Have both stylus and touch data, beginning fusion");
1719#endif
1720 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1721 } else if (timeout) {
1722#if DEBUG_STYLUS_FUSION
1723 ALOGD("Timeout expired, assuming touch is not a stylus.");
1724#endif
1725 resetExternalStylus();
1726 } else {
1727 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1728 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1729 }
1730#if DEBUG_STYLUS_FUSION
1731 ALOGD("No stylus data but stylus is connected, requesting timeout "
1732 "(%" PRId64 "ms)",
1733 mExternalStylusFusionTimeout);
1734#endif
1735 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1736 return true;
1737 }
1738 }
1739
1740 // Check if the stylus pointer has gone up.
1741 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1742#if DEBUG_STYLUS_FUSION
1743 ALOGD("Stylus pointer is going up");
1744#endif
1745 mExternalStylusId = -1;
1746 }
1747
1748 return false;
1749}
1750
1751void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001752 if (mDeviceMode == DeviceMode::POINTER) {
1753 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001754 // Since this is a synthetic event, we can consider its latency to be zero
1755 const nsecs_t readTime = when;
1756 dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001757 }
Michael Wright227c5542020-07-02 18:30:52 +01001758 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001759 if (mExternalStylusFusionTimeout < when) {
1760 processRawTouches(true /*timeout*/);
1761 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1762 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1763 }
1764 }
1765}
1766
1767void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1768 mExternalStylusState.copyFrom(state);
1769 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1770 // We're either in the middle of a fused stream of data or we're waiting on data before
1771 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1772 // data.
1773 mExternalStylusDataPending = true;
1774 processRawTouches(false /*timeout*/);
1775 }
1776}
1777
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001778bool TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001779 // Check for release of a virtual key.
1780 if (mCurrentVirtualKey.down) {
1781 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1782 // Pointer went up while virtual key was down.
1783 mCurrentVirtualKey.down = false;
1784 if (!mCurrentVirtualKey.ignored) {
1785#if DEBUG_VIRTUAL_KEYS
1786 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1787 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1788#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001789 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001790 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1791 }
1792 return true;
1793 }
1794
1795 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1796 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1797 const RawPointerData::Pointer& pointer =
1798 mCurrentRawState.rawPointerData.pointerForId(id);
1799 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1800 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1801 // Pointer is still within the space of the virtual key.
1802 return true;
1803 }
1804 }
1805
1806 // Pointer left virtual key area or another pointer also went down.
1807 // Send key cancellation but do not consume the touch yet.
1808 // This is useful when the user swipes through from the virtual key area
1809 // into the main display surface.
1810 mCurrentVirtualKey.down = false;
1811 if (!mCurrentVirtualKey.ignored) {
1812#if DEBUG_VIRTUAL_KEYS
1813 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1814 mCurrentVirtualKey.scanCode);
1815#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001816 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001817 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1818 AKEY_EVENT_FLAG_CANCELED);
1819 }
1820 }
1821
1822 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1823 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1824 // Pointer just went down. Check for virtual key press or off-screen touches.
1825 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1826 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Prabir Pradhan1728b212021-10-19 16:00:03 -07001827 // Skip checking whether the pointer is inside the physical frame if the device is in
1828 // unscaled mode.
1829 if (!isPointInsidePhysicalFrame(pointer.x, pointer.y) &&
1830 mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001831 // If exactly one pointer went down, check for virtual key hit.
1832 // Otherwise we will drop the entire stroke.
1833 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1834 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1835 if (virtualKey) {
1836 mCurrentVirtualKey.down = true;
1837 mCurrentVirtualKey.downTime = when;
1838 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1839 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1840 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001841 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1842 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001843
1844 if (!mCurrentVirtualKey.ignored) {
1845#if DEBUG_VIRTUAL_KEYS
1846 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1847 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1848#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001849 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_DOWN,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001850 AKEY_EVENT_FLAG_FROM_SYSTEM |
1851 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1852 }
1853 }
1854 }
1855 return true;
1856 }
1857 }
1858
1859 // Disable all virtual key touches that happen within a short time interval of the
1860 // most recent touch within the screen area. The idea is to filter out stray
1861 // virtual key presses when interacting with the touch screen.
1862 //
1863 // Problems we're trying to solve:
1864 //
1865 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1866 // virtual key area that is implemented by a separate touch panel and accidentally
1867 // triggers a virtual key.
1868 //
1869 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1870 // area and accidentally triggers a virtual key. This often happens when virtual keys
1871 // are layed out below the screen near to where the on screen keyboard's space bar
1872 // is displayed.
1873 if (mConfig.virtualKeyQuietTime > 0 &&
1874 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001875 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001876 }
1877 return false;
1878}
1879
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001880void TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001881 int32_t keyEventAction, int32_t keyEventFlags) {
1882 int32_t keyCode = mCurrentVirtualKey.keyCode;
1883 int32_t scanCode = mCurrentVirtualKey.scanCode;
1884 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001885 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001886 policyFlags |= POLICY_FLAG_VIRTUAL;
1887
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001888 NotifyKeyArgs args(getContext()->getNextId(), when, readTime, getDeviceId(),
1889 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1890 keyEventFlags, keyCode, scanCode, metaState, downTime);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001891 getListener().notifyKey(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001892}
1893
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001894void TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001895 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1896 if (!currentIdBits.isEmpty()) {
1897 int32_t metaState = getContext()->getGlobalMetaState();
1898 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001899 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
1900 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001901 mCurrentCookedState.cookedPointerData.pointerProperties,
1902 mCurrentCookedState.cookedPointerData.pointerCoords,
1903 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1904 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1905 mCurrentMotionAborted = true;
1906 }
1907}
1908
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001909void TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001910 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1911 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1912 int32_t metaState = getContext()->getGlobalMetaState();
1913 int32_t buttonState = mCurrentCookedState.buttonState;
1914
1915 if (currentIdBits == lastIdBits) {
1916 if (!currentIdBits.isEmpty()) {
1917 // No pointer id changes so this is a move event.
1918 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001919 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1920 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001921 mCurrentCookedState.cookedPointerData.pointerProperties,
1922 mCurrentCookedState.cookedPointerData.pointerCoords,
1923 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1924 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1925 }
1926 } else {
1927 // There may be pointers going up and pointers going down and pointers moving
1928 // all at the same time.
1929 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1930 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1931 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1932 BitSet32 dispatchedIdBits(lastIdBits.value);
1933
1934 // Update last coordinates of pointers that have moved so that we observe the new
1935 // pointer positions at the same time as other pointers that have just gone up.
1936 bool moveNeeded =
1937 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1938 mCurrentCookedState.cookedPointerData.pointerCoords,
1939 mCurrentCookedState.cookedPointerData.idToIndex,
1940 mLastCookedState.cookedPointerData.pointerProperties,
1941 mLastCookedState.cookedPointerData.pointerCoords,
1942 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1943 if (buttonState != mLastCookedState.buttonState) {
1944 moveNeeded = true;
1945 }
1946
1947 // Dispatch pointer up events.
1948 while (!upIdBits.isEmpty()) {
1949 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001950 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001951 if (isCanceled) {
1952 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1953 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001954 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
arthurhungcc7f9802020-04-30 17:55:40 +08001955 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001956 mLastCookedState.cookedPointerData.pointerProperties,
1957 mLastCookedState.cookedPointerData.pointerCoords,
1958 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1959 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1960 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001961 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001962 }
1963
1964 // Dispatch move events if any of the remaining pointers moved from their old locations.
1965 // Although applications receive new locations as part of individual pointer up
1966 // events, they do not generally handle them except when presented in a move event.
1967 if (moveNeeded && !moveIdBits.isEmpty()) {
1968 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001969 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1970 metaState, buttonState, 0,
1971 mCurrentCookedState.cookedPointerData.pointerProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001972 mCurrentCookedState.cookedPointerData.pointerCoords,
1973 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1974 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1975 }
1976
1977 // Dispatch pointer down events using the new pointer locations.
1978 while (!downIdBits.isEmpty()) {
1979 uint32_t downId = downIdBits.clearFirstMarkedBit();
1980 dispatchedIdBits.markBit(downId);
1981
1982 if (dispatchedIdBits.count() == 1) {
1983 // First pointer is going down. Set down time.
1984 mDownTime = when;
1985 }
1986
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001987 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
1988 0, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001989 mCurrentCookedState.cookedPointerData.pointerProperties,
1990 mCurrentCookedState.cookedPointerData.pointerCoords,
1991 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1992 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1993 }
1994 }
1995}
1996
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001997void TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001998 if (mSentHoverEnter &&
1999 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2000 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2001 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002002 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
2003 metaState, mLastCookedState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002004 mLastCookedState.cookedPointerData.pointerProperties,
2005 mLastCookedState.cookedPointerData.pointerCoords,
2006 mLastCookedState.cookedPointerData.idToIndex,
2007 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
2008 mOrientedYPrecision, mDownTime);
2009 mSentHoverEnter = false;
2010 }
2011}
2012
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002013void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2014 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002015 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2016 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2017 int32_t metaState = getContext()->getGlobalMetaState();
2018 if (!mSentHoverEnter) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002019 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
2020 0, 0, metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002021 mCurrentCookedState.cookedPointerData.pointerProperties,
2022 mCurrentCookedState.cookedPointerData.pointerCoords,
2023 mCurrentCookedState.cookedPointerData.idToIndex,
2024 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2025 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2026 mSentHoverEnter = true;
2027 }
2028
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002029 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2030 metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002031 mCurrentCookedState.cookedPointerData.pointerProperties,
2032 mCurrentCookedState.cookedPointerData.pointerCoords,
2033 mCurrentCookedState.cookedPointerData.idToIndex,
2034 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2035 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2036 }
2037}
2038
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002039void TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002040 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2041 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2042 const int32_t metaState = getContext()->getGlobalMetaState();
2043 int32_t buttonState = mLastCookedState.buttonState;
2044 while (!releasedButtons.isEmpty()) {
2045 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2046 buttonState &= ~actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002047 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002048 actionButton, 0, metaState, buttonState, 0,
2049 mCurrentCookedState.cookedPointerData.pointerProperties,
2050 mCurrentCookedState.cookedPointerData.pointerCoords,
2051 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2052 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2053 }
2054}
2055
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002056void TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002057 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2058 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2059 const int32_t metaState = getContext()->getGlobalMetaState();
2060 int32_t buttonState = mLastCookedState.buttonState;
2061 while (!pressedButtons.isEmpty()) {
2062 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2063 buttonState |= actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002064 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2065 actionButton, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002066 mCurrentCookedState.cookedPointerData.pointerProperties,
2067 mCurrentCookedState.cookedPointerData.pointerCoords,
2068 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2069 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2070 }
2071}
2072
2073const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2074 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2075 return cookedPointerData.touchingIdBits;
2076 }
2077 return cookedPointerData.hoveringIdBits;
2078}
2079
2080void TouchInputMapper::cookPointerData() {
2081 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2082
2083 mCurrentCookedState.cookedPointerData.clear();
2084 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2085 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2086 mCurrentRawState.rawPointerData.hoveringIdBits;
2087 mCurrentCookedState.cookedPointerData.touchingIdBits =
2088 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002089 mCurrentCookedState.cookedPointerData.canceledIdBits =
2090 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002091
2092 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2093 mCurrentCookedState.buttonState = 0;
2094 } else {
2095 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2096 }
2097
2098 // Walk through the the active pointers and map device coordinates onto
Prabir Pradhan1728b212021-10-19 16:00:03 -07002099 // display coordinates and adjust for display orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002100 for (uint32_t i = 0; i < currentPointerCount; i++) {
2101 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2102
2103 // Size
2104 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2105 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002106 case Calibration::SizeCalibration::GEOMETRIC:
2107 case Calibration::SizeCalibration::DIAMETER:
2108 case Calibration::SizeCalibration::BOX:
2109 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002110 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2111 touchMajor = in.touchMajor;
2112 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2113 toolMajor = in.toolMajor;
2114 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2115 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2116 : in.touchMajor;
2117 } else if (mRawPointerAxes.touchMajor.valid) {
2118 toolMajor = touchMajor = in.touchMajor;
2119 toolMinor = touchMinor =
2120 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2121 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2122 : in.touchMajor;
2123 } else if (mRawPointerAxes.toolMajor.valid) {
2124 touchMajor = toolMajor = in.toolMajor;
2125 touchMinor = toolMinor =
2126 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2127 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2128 : in.toolMajor;
2129 } else {
2130 ALOG_ASSERT(false,
2131 "No touch or tool axes. "
2132 "Size calibration should have been resolved to NONE.");
2133 touchMajor = 0;
2134 touchMinor = 0;
2135 toolMajor = 0;
2136 toolMinor = 0;
2137 size = 0;
2138 }
2139
2140 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2141 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2142 if (touchingCount > 1) {
2143 touchMajor /= touchingCount;
2144 touchMinor /= touchingCount;
2145 toolMajor /= touchingCount;
2146 toolMinor /= touchingCount;
2147 size /= touchingCount;
2148 }
2149 }
2150
Michael Wright227c5542020-07-02 18:30:52 +01002151 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002152 touchMajor *= mGeometricScale;
2153 touchMinor *= mGeometricScale;
2154 toolMajor *= mGeometricScale;
2155 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002156 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002157 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2158 touchMinor = touchMajor;
2159 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2160 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002161 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002162 touchMinor = touchMajor;
2163 toolMinor = toolMajor;
2164 }
2165
2166 mCalibration.applySizeScaleAndBias(&touchMajor);
2167 mCalibration.applySizeScaleAndBias(&touchMinor);
2168 mCalibration.applySizeScaleAndBias(&toolMajor);
2169 mCalibration.applySizeScaleAndBias(&toolMinor);
2170 size *= mSizeScale;
2171 break;
2172 default:
2173 touchMajor = 0;
2174 touchMinor = 0;
2175 toolMajor = 0;
2176 toolMinor = 0;
2177 size = 0;
2178 break;
2179 }
2180
2181 // Pressure
2182 float pressure;
2183 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002184 case Calibration::PressureCalibration::PHYSICAL:
2185 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002186 pressure = in.pressure * mPressureScale;
2187 break;
2188 default:
2189 pressure = in.isHovering ? 0 : 1;
2190 break;
2191 }
2192
2193 // Tilt and Orientation
2194 float tilt;
2195 float orientation;
2196 if (mHaveTilt) {
2197 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2198 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2199 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2200 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2201 } else {
2202 tilt = 0;
2203
2204 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002205 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002206 orientation = in.orientation * mOrientationScale;
2207 break;
Michael Wright227c5542020-07-02 18:30:52 +01002208 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002209 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2210 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2211 if (c1 != 0 || c2 != 0) {
2212 orientation = atan2f(c1, c2) * 0.5f;
2213 float confidence = hypotf(c1, c2);
2214 float scale = 1.0f + confidence / 16.0f;
2215 touchMajor *= scale;
2216 touchMinor /= scale;
2217 toolMajor *= scale;
2218 toolMinor /= scale;
2219 } else {
2220 orientation = 0;
2221 }
2222 break;
2223 }
2224 default:
2225 orientation = 0;
2226 }
2227 }
2228
2229 // Distance
2230 float distance;
2231 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002232 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002233 distance = in.distance * mDistanceScale;
2234 break;
2235 default:
2236 distance = 0;
2237 }
2238
2239 // Coverage
2240 int32_t rawLeft, rawTop, rawRight, rawBottom;
2241 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002242 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002243 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2244 rawRight = in.toolMinor & 0x0000ffff;
2245 rawBottom = in.toolMajor & 0x0000ffff;
2246 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2247 break;
2248 default:
2249 rawLeft = rawTop = rawRight = rawBottom = 0;
2250 break;
2251 }
2252
2253 // Adjust X,Y coords for device calibration
2254 // TODO: Adjust coverage coords?
2255 float xTransformed = in.x, yTransformed = in.y;
2256 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002257 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002258
Prabir Pradhan1728b212021-10-19 16:00:03 -07002259 // Adjust X, Y, and coverage coords for input device orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002260 float left, top, right, bottom;
2261
Prabir Pradhan1728b212021-10-19 16:00:03 -07002262 switch (mInputDeviceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002263 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002264 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
2265 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2266 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2267 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002268 orientation -= M_PI_2;
2269 if (mOrientedRanges.haveOrientation &&
2270 orientation < mOrientedRanges.orientation.min) {
2271 orientation +=
2272 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2273 }
2274 break;
2275 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002276 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2277 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002278 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2279 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002280 orientation -= M_PI;
2281 if (mOrientedRanges.haveOrientation &&
2282 orientation < mOrientedRanges.orientation.min) {
2283 orientation +=
2284 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2285 }
2286 break;
2287 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002288 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2289 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07002290 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2291 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002292 orientation += M_PI_2;
2293 if (mOrientedRanges.haveOrientation &&
2294 orientation > mOrientedRanges.orientation.max) {
2295 orientation -=
2296 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2297 }
2298 break;
2299 default:
Prabir Pradhan1728b212021-10-19 16:00:03 -07002300 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
2301 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
2302 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
2303 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002304 break;
2305 }
2306
2307 // Write output coords.
2308 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2309 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002310 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2311 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002312 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2313 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2314 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2315 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2316 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2317 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2318 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002319 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002320 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2321 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2322 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2323 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2324 } else {
2325 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2326 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2327 }
2328
Chris Ye364fdb52020-08-05 15:07:56 -07002329 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002330 uint32_t id = in.id;
2331 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2332 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2333 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2334 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2335 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2336 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2337 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2338 }
2339
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002340 // Write output properties.
2341 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002342 properties.clear();
2343 properties.id = id;
2344 properties.toolType = in.toolType;
2345
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002346 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002347 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002348 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002349 }
2350}
2351
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002352void TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002353 PointerUsage pointerUsage) {
2354 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002355 abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002356 mPointerUsage = pointerUsage;
2357 }
2358
2359 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002360 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002361 dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002362 break;
Michael Wright227c5542020-07-02 18:30:52 +01002363 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002364 dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002365 break;
Michael Wright227c5542020-07-02 18:30:52 +01002366 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002367 dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002368 break;
Michael Wright227c5542020-07-02 18:30:52 +01002369 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002370 break;
2371 }
2372}
2373
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002374void TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002375 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002376 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002377 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 Vishniakou58ba3d12021-02-11 01:31:07 +00002380 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 Vishniakou58ba3d12021-02-11 01:31:07 +00002383 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;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002390}
2391
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002392void TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
2393 bool isTimeout) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002394 // Update current gesture coordinates.
2395 bool cancelPreviousGesture, finishPreviousGesture;
2396 bool sendEvents =
2397 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2398 if (!sendEvents) {
2399 return;
2400 }
2401 if (finishPreviousGesture) {
2402 cancelPreviousGesture = false;
2403 }
2404
2405 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002406 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002407 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002408 if (finishPreviousGesture || cancelPreviousGesture) {
2409 mPointerController->clearSpots();
2410 }
2411
Michael Wright227c5542020-07-02 18:30:52 +01002412 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002413 setTouchSpots(mPointerGesture.currentGestureCoords,
2414 mPointerGesture.currentGestureIdToIndex,
2415 mPointerGesture.currentGestureIdBits, mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002416 }
2417 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002418 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002419 }
2420
2421 // Show or hide the pointer if needed.
2422 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002423 case PointerGesture::Mode::NEUTRAL:
2424 case PointerGesture::Mode::QUIET:
2425 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2426 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002427 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002428 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002429 }
2430 break;
Michael Wright227c5542020-07-02 18:30:52 +01002431 case PointerGesture::Mode::TAP:
2432 case PointerGesture::Mode::TAP_DRAG:
2433 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2434 case PointerGesture::Mode::HOVER:
2435 case PointerGesture::Mode::PRESS:
2436 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002437 // Unfade the pointer when the current gesture manipulates the
2438 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002439 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002440 break;
Michael Wright227c5542020-07-02 18:30:52 +01002441 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002442 // Fade the pointer when the current gesture manipulates a different
2443 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002444 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002445 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002446 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002447 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002448 }
2449 break;
2450 }
2451
2452 // Send events!
2453 int32_t metaState = getContext()->getGlobalMetaState();
2454 int32_t buttonState = mCurrentCookedState.buttonState;
2455
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002456 uint32_t flags = 0;
2457
2458 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2459 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2460 }
2461
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002462 // Update last coordinates of pointers that have moved so that we observe the new
2463 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002464 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2465 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2466 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2467 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2468 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2469 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002470 bool moveNeeded = false;
2471 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2472 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2473 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2474 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2475 mPointerGesture.lastGestureIdBits.value);
2476 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2477 mPointerGesture.currentGestureCoords,
2478 mPointerGesture.currentGestureIdToIndex,
2479 mPointerGesture.lastGestureProperties,
2480 mPointerGesture.lastGestureCoords,
2481 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2482 if (buttonState != mLastCookedState.buttonState) {
2483 moveNeeded = true;
2484 }
2485 }
2486
2487 // Send motion events for all pointers that went up or were canceled.
2488 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2489 if (!dispatchedGestureIdBits.isEmpty()) {
2490 if (cancelPreviousGesture) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002491 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0,
2492 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002493 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2494 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2495 mPointerGesture.downTime);
2496
2497 dispatchedGestureIdBits.clear();
2498 } else {
2499 BitSet32 upGestureIdBits;
2500 if (finishPreviousGesture) {
2501 upGestureIdBits = dispatchedGestureIdBits;
2502 } else {
2503 upGestureIdBits.value =
2504 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2505 }
2506 while (!upGestureIdBits.isEmpty()) {
2507 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2508
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002509 dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002510 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState, buttonState,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002511 AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002512 mPointerGesture.lastGestureCoords,
2513 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2514 0, mPointerGesture.downTime);
2515
2516 dispatchedGestureIdBits.clearBit(id);
2517 }
2518 }
2519 }
2520
2521 // Send motion events for all pointers that moved.
2522 if (moveNeeded) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002523 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002524 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002525 mPointerGesture.currentGestureProperties,
2526 mPointerGesture.currentGestureCoords,
2527 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2528 mPointerGesture.downTime);
2529 }
2530
2531 // Send motion events for all pointers that went down.
2532 if (down) {
2533 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2534 ~dispatchedGestureIdBits.value);
2535 while (!downGestureIdBits.isEmpty()) {
2536 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2537 dispatchedGestureIdBits.markBit(id);
2538
2539 if (dispatchedGestureIdBits.count() == 1) {
2540 mPointerGesture.downTime = when;
2541 }
2542
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002543 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002544 0, flags, metaState, buttonState, 0,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002545 mPointerGesture.currentGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002546 mPointerGesture.currentGestureCoords,
2547 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2548 0, mPointerGesture.downTime);
2549 }
2550 }
2551
2552 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002553 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002554 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2555 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002556 mPointerGesture.currentGestureProperties,
2557 mPointerGesture.currentGestureCoords,
2558 mPointerGesture.currentGestureIdToIndex,
2559 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2560 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2561 // Synthesize a hover move event after all pointers go up to indicate that
2562 // the pointer is hovering again even if the user is not currently touching
2563 // the touch pad. This ensures that a view will receive a fresh hover enter
2564 // event after a tap.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002565 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002566
2567 PointerProperties pointerProperties;
2568 pointerProperties.clear();
2569 pointerProperties.id = 0;
2570 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2571
2572 PointerCoords pointerCoords;
2573 pointerCoords.clear();
2574 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2575 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2576
2577 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002578 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002579 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002580 metaState, buttonState, MotionClassification::NONE,
2581 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
2582 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002583 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002584 }
2585
2586 // Update state.
2587 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2588 if (!down) {
2589 mPointerGesture.lastGestureIdBits.clear();
2590 } else {
2591 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2592 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2593 uint32_t id = idBits.clearFirstMarkedBit();
2594 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2595 mPointerGesture.lastGestureProperties[index].copyFrom(
2596 mPointerGesture.currentGestureProperties[index]);
2597 mPointerGesture.lastGestureCoords[index].copyFrom(
2598 mPointerGesture.currentGestureCoords[index]);
2599 mPointerGesture.lastGestureIdToIndex[id] = index;
2600 }
2601 }
2602}
2603
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002604void TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002605 // Cancel previously dispatches pointers.
2606 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2607 int32_t metaState = getContext()->getGlobalMetaState();
2608 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002609 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
2610 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002611 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2612 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2613 0, 0, mPointerGesture.downTime);
2614 }
2615
2616 // Reset the current pointer gesture.
2617 mPointerGesture.reset();
2618 mPointerVelocityControl.reset();
2619
2620 // Remove any current spots.
2621 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002622 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002623 mPointerController->clearSpots();
2624 }
2625}
2626
2627bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2628 bool* outFinishPreviousGesture, bool isTimeout) {
2629 *outCancelPreviousGesture = false;
2630 *outFinishPreviousGesture = false;
2631
2632 // Handle TAP timeout.
2633 if (isTimeout) {
2634#if DEBUG_GESTURES
2635 ALOGD("Gestures: Processing timeout");
2636#endif
2637
Michael Wright227c5542020-07-02 18:30:52 +01002638 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002639 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2640 // The tap/drag timeout has not yet expired.
2641 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2642 mConfig.pointerGestureTapDragInterval);
2643 } else {
2644 // The tap is finished.
2645#if DEBUG_GESTURES
2646 ALOGD("Gestures: TAP finished");
2647#endif
2648 *outFinishPreviousGesture = true;
2649
2650 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002651 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002652 mPointerGesture.currentGestureIdBits.clear();
2653
2654 mPointerVelocityControl.reset();
2655 return true;
2656 }
2657 }
2658
2659 // We did not handle this timeout.
2660 return false;
2661 }
2662
2663 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2664 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2665
2666 // Update the velocity tracker.
2667 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002668 std::vector<VelocityTracker::Position> positions;
2669 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002670 uint32_t id = idBits.clearFirstMarkedBit();
2671 const RawPointerData::Pointer& pointer =
2672 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002673 float x = pointer.x * mPointerXMovementScale;
2674 float y = pointer.y * mPointerYMovementScale;
2675 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002676 }
2677 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2678 positions);
2679 }
2680
2681 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2682 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002683 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2684 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2685 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002686 mPointerGesture.resetTap();
2687 }
2688
2689 // Pick a new active touch id if needed.
2690 // Choose an arbitrary pointer that just went down, if there is one.
2691 // Otherwise choose an arbitrary remaining pointer.
2692 // This guarantees we always have an active touch id when there is at least one pointer.
2693 // We keep the same active touch id for as long as possible.
2694 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2695 int32_t activeTouchId = lastActiveTouchId;
2696 if (activeTouchId < 0) {
2697 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2698 activeTouchId = mPointerGesture.activeTouchId =
2699 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2700 mPointerGesture.firstTouchTime = when;
2701 }
2702 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2703 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2704 activeTouchId = mPointerGesture.activeTouchId =
2705 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2706 } else {
2707 activeTouchId = mPointerGesture.activeTouchId = -1;
2708 }
2709 }
2710
2711 // Determine whether we are in quiet time.
2712 bool isQuietTime = false;
2713 if (activeTouchId < 0) {
2714 mPointerGesture.resetQuietTime();
2715 } else {
2716 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2717 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002718 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2719 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2720 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002721 currentFingerCount < 2) {
2722 // Enter quiet time when exiting swipe or freeform state.
2723 // This is to prevent accidentally entering the hover state and flinging the
2724 // pointer when finishing a swipe and there is still one pointer left onscreen.
2725 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002726 } else if (mPointerGesture.lastGestureMode ==
2727 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002728 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2729 // Enter quiet time when releasing the button and there are still two or more
2730 // fingers down. This may indicate that one finger was used to press the button
2731 // but it has not gone up yet.
2732 isQuietTime = true;
2733 }
2734 if (isQuietTime) {
2735 mPointerGesture.quietTime = when;
2736 }
2737 }
2738 }
2739
2740 // Switch states based on button and pointer state.
2741 if (isQuietTime) {
2742 // Case 1: Quiet time. (QUIET)
2743#if DEBUG_GESTURES
2744 ALOGD("Gestures: QUIET for next %0.3fms",
2745 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2746#endif
Michael Wright227c5542020-07-02 18:30:52 +01002747 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002748 *outFinishPreviousGesture = true;
2749 }
2750
2751 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002752 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002753 mPointerGesture.currentGestureIdBits.clear();
2754
2755 mPointerVelocityControl.reset();
2756 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2757 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2758 // The pointer follows the active touch point.
2759 // Emit DOWN, MOVE, UP events at the pointer location.
2760 //
2761 // Only the active touch matters; other fingers are ignored. This policy helps
2762 // to handle the case where the user places a second finger on the touch pad
2763 // to apply the necessary force to depress an integrated button below the surface.
2764 // We don't want the second finger to be delivered to applications.
2765 //
2766 // For this to work well, we need to make sure to track the pointer that is really
2767 // active. If the user first puts one finger down to click then adds another
2768 // finger to drag then the active pointer should switch to the finger that is
2769 // being dragged.
2770#if DEBUG_GESTURES
2771 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2772 "currentFingerCount=%d",
2773 activeTouchId, currentFingerCount);
2774#endif
2775 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002776 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002777 *outFinishPreviousGesture = true;
2778 mPointerGesture.activeGestureId = 0;
2779 }
2780
2781 // Switch pointers if needed.
2782 // Find the fastest pointer and follow it.
2783 if (activeTouchId >= 0 && currentFingerCount > 1) {
2784 int32_t bestId = -1;
2785 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2786 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2787 uint32_t id = idBits.clearFirstMarkedBit();
2788 float vx, vy;
2789 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2790 float speed = hypotf(vx, vy);
2791 if (speed > bestSpeed) {
2792 bestId = id;
2793 bestSpeed = speed;
2794 }
2795 }
2796 }
2797 if (bestId >= 0 && bestId != activeTouchId) {
2798 mPointerGesture.activeTouchId = activeTouchId = bestId;
2799#if DEBUG_GESTURES
2800 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2801 "bestId=%d, bestSpeed=%0.3f",
2802 bestId, bestSpeed);
2803#endif
2804 }
2805 }
2806
2807 float deltaX = 0, deltaY = 0;
2808 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2809 const RawPointerData::Pointer& currentPointer =
2810 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2811 const RawPointerData::Pointer& lastPointer =
2812 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2813 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2814 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2815
Prabir Pradhan1728b212021-10-19 16:00:03 -07002816 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002817 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2818
2819 // Move the pointer using a relative motion.
2820 // When using spots, the click will occur at the position of the anchor
2821 // spot and all other spots will move there.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002822 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002823 } else {
2824 mPointerVelocityControl.reset();
2825 }
2826
Prabir Pradhand7482e72021-03-09 13:54:55 -08002827 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002828
Michael Wright227c5542020-07-02 18:30:52 +01002829 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002830 mPointerGesture.currentGestureIdBits.clear();
2831 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2832 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2833 mPointerGesture.currentGestureProperties[0].clear();
2834 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2835 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2836 mPointerGesture.currentGestureCoords[0].clear();
2837 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2838 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2839 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2840 } else if (currentFingerCount == 0) {
2841 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002842 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002843 *outFinishPreviousGesture = true;
2844 }
2845
2846 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2847 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2848 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002849 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2850 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002851 lastFingerCount == 1) {
2852 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002853 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002854 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2855 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2856#if DEBUG_GESTURES
2857 ALOGD("Gestures: TAP");
2858#endif
2859
2860 mPointerGesture.tapUpTime = when;
2861 getContext()->requestTimeoutAtTime(when +
2862 mConfig.pointerGestureTapDragInterval);
2863
2864 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002865 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002866 mPointerGesture.currentGestureIdBits.clear();
2867 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2868 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2869 mPointerGesture.currentGestureProperties[0].clear();
2870 mPointerGesture.currentGestureProperties[0].id =
2871 mPointerGesture.activeGestureId;
2872 mPointerGesture.currentGestureProperties[0].toolType =
2873 AMOTION_EVENT_TOOL_TYPE_FINGER;
2874 mPointerGesture.currentGestureCoords[0].clear();
2875 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2876 mPointerGesture.tapX);
2877 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2878 mPointerGesture.tapY);
2879 mPointerGesture.currentGestureCoords[0]
2880 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2881
2882 tapped = true;
2883 } else {
2884#if DEBUG_GESTURES
2885 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2886 y - mPointerGesture.tapY);
2887#endif
2888 }
2889 } else {
2890#if DEBUG_GESTURES
2891 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2892 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2893 (when - mPointerGesture.tapDownTime) * 0.000001f);
2894 } else {
2895 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2896 }
2897#endif
2898 }
2899 }
2900
2901 mPointerVelocityControl.reset();
2902
2903 if (!tapped) {
2904#if DEBUG_GESTURES
2905 ALOGD("Gestures: NEUTRAL");
2906#endif
2907 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002908 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002909 mPointerGesture.currentGestureIdBits.clear();
2910 }
2911 } else if (currentFingerCount == 1) {
2912 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2913 // The pointer follows the active touch point.
2914 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2915 // When in TAP_DRAG, emit MOVE events at the pointer location.
2916 ALOG_ASSERT(activeTouchId >= 0);
2917
Michael Wright227c5542020-07-02 18:30:52 +01002918 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2919 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002920 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002921 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002922 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2923 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002924 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002925 } else {
2926#if DEBUG_GESTURES
2927 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2928 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2929#endif
2930 }
2931 } else {
2932#if DEBUG_GESTURES
2933 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2934 (when - mPointerGesture.tapUpTime) * 0.000001f);
2935#endif
2936 }
Michael Wright227c5542020-07-02 18:30:52 +01002937 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2938 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002939 }
2940
2941 float deltaX = 0, deltaY = 0;
2942 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2943 const RawPointerData::Pointer& currentPointer =
2944 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2945 const RawPointerData::Pointer& lastPointer =
2946 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2947 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2948 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2949
Prabir Pradhan1728b212021-10-19 16:00:03 -07002950 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002951 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2952
2953 // Move the pointer using a relative motion.
2954 // When using spots, the hover or drag will occur at the position of the anchor spot.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002955 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002956 } else {
2957 mPointerVelocityControl.reset();
2958 }
2959
2960 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002961 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002962#if DEBUG_GESTURES
2963 ALOGD("Gestures: TAP_DRAG");
2964#endif
2965 down = true;
2966 } else {
2967#if DEBUG_GESTURES
2968 ALOGD("Gestures: HOVER");
2969#endif
Michael Wright227c5542020-07-02 18:30:52 +01002970 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002971 *outFinishPreviousGesture = true;
2972 }
2973 mPointerGesture.activeGestureId = 0;
2974 down = false;
2975 }
2976
Prabir Pradhand7482e72021-03-09 13:54:55 -08002977 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002978
2979 mPointerGesture.currentGestureIdBits.clear();
2980 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2981 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2982 mPointerGesture.currentGestureProperties[0].clear();
2983 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2984 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2985 mPointerGesture.currentGestureCoords[0].clear();
2986 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2987 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2988 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2989 down ? 1.0f : 0.0f);
2990
2991 if (lastFingerCount == 0 && currentFingerCount != 0) {
2992 mPointerGesture.resetTap();
2993 mPointerGesture.tapDownTime = when;
2994 mPointerGesture.tapX = x;
2995 mPointerGesture.tapY = y;
2996 }
2997 } else {
2998 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2999 // We need to provide feedback for each finger that goes down so we cannot wait
3000 // for the fingers to move before deciding what to do.
3001 //
3002 // The ambiguous case is deciding what to do when there are two fingers down but they
3003 // have not moved enough to determine whether they are part of a drag or part of a
3004 // freeform gesture, or just a press or long-press at the pointer location.
3005 //
3006 // When there are two fingers we start with the PRESS hypothesis and we generate a
3007 // down at the pointer location.
3008 //
3009 // When the two fingers move enough or when additional fingers are added, we make
3010 // a decision to transition into SWIPE or FREEFORM mode accordingly.
3011 ALOG_ASSERT(activeTouchId >= 0);
3012
3013 bool settled = when >=
3014 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01003015 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3016 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3017 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003018 *outFinishPreviousGesture = true;
3019 } else if (!settled && currentFingerCount > lastFingerCount) {
3020 // Additional pointers have gone down but not yet settled.
3021 // Reset the gesture.
3022#if DEBUG_GESTURES
3023 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
3024 "settle time remaining %0.3fms",
3025 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3026 when) * 0.000001f);
3027#endif
3028 *outCancelPreviousGesture = true;
3029 } else {
3030 // Continue previous gesture.
3031 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3032 }
3033
3034 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01003035 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003036 mPointerGesture.activeGestureId = 0;
3037 mPointerGesture.referenceIdBits.clear();
3038 mPointerVelocityControl.reset();
3039
3040 // Use the centroid and pointer location as the reference points for the gesture.
3041#if DEBUG_GESTURES
3042 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3043 "settle time remaining %0.3fms",
3044 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3045 when) * 0.000001f);
3046#endif
3047 mCurrentRawState.rawPointerData
3048 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3049 &mPointerGesture.referenceTouchY);
Prabir Pradhand7482e72021-03-09 13:54:55 -08003050 auto [x, y] = getMouseCursorPosition();
3051 mPointerGesture.referenceGestureX = x;
3052 mPointerGesture.referenceGestureY = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003053 }
3054
3055 // Clear the reference deltas for fingers not yet included in the reference calculation.
3056 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3057 ~mPointerGesture.referenceIdBits.value);
3058 !idBits.isEmpty();) {
3059 uint32_t id = idBits.clearFirstMarkedBit();
3060 mPointerGesture.referenceDeltas[id].dx = 0;
3061 mPointerGesture.referenceDeltas[id].dy = 0;
3062 }
3063 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3064
3065 // Add delta for all fingers and calculate a common movement delta.
3066 float commonDeltaX = 0, commonDeltaY = 0;
3067 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3068 mCurrentCookedState.fingerIdBits.value);
3069 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3070 bool first = (idBits == commonIdBits);
3071 uint32_t id = idBits.clearFirstMarkedBit();
3072 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3073 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3074 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3075 delta.dx += cpd.x - lpd.x;
3076 delta.dy += cpd.y - lpd.y;
3077
3078 if (first) {
3079 commonDeltaX = delta.dx;
3080 commonDeltaY = delta.dy;
3081 } else {
3082 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3083 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3084 }
3085 }
3086
3087 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003088 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003089 float dist[MAX_POINTER_ID + 1];
3090 int32_t distOverThreshold = 0;
3091 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3092 uint32_t id = idBits.clearFirstMarkedBit();
3093 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3094 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3095 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3096 distOverThreshold += 1;
3097 }
3098 }
3099
3100 // Only transition when at least two pointers have moved further than
3101 // the minimum distance threshold.
3102 if (distOverThreshold >= 2) {
3103 if (currentFingerCount > 2) {
3104 // There are more than two pointers, switch to FREEFORM.
3105#if DEBUG_GESTURES
3106 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3107 currentFingerCount);
3108#endif
3109 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003110 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003111 } else {
3112 // There are exactly two pointers.
3113 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3114 uint32_t id1 = idBits.clearFirstMarkedBit();
3115 uint32_t id2 = idBits.firstMarkedBit();
3116 const RawPointerData::Pointer& p1 =
3117 mCurrentRawState.rawPointerData.pointerForId(id1);
3118 const RawPointerData::Pointer& p2 =
3119 mCurrentRawState.rawPointerData.pointerForId(id2);
3120 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3121 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3122 // There are two pointers but they are too far apart for a SWIPE,
3123 // switch to FREEFORM.
3124#if DEBUG_GESTURES
3125 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3126 mutualDistance, mPointerGestureMaxSwipeWidth);
3127#endif
3128 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003129 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003130 } else {
3131 // There are two pointers. Wait for both pointers to start moving
3132 // before deciding whether this is a SWIPE or FREEFORM gesture.
3133 float dist1 = dist[id1];
3134 float dist2 = dist[id2];
3135 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3136 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3137 // Calculate the dot product of the displacement vectors.
3138 // When the vectors are oriented in approximately the same direction,
3139 // the angle betweeen them is near zero and the cosine of the angle
3140 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3141 // mag(v2).
3142 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3143 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3144 float dx1 = delta1.dx * mPointerXZoomScale;
3145 float dy1 = delta1.dy * mPointerYZoomScale;
3146 float dx2 = delta2.dx * mPointerXZoomScale;
3147 float dy2 = delta2.dy * mPointerYZoomScale;
3148 float dot = dx1 * dx2 + dy1 * dy2;
3149 float cosine = dot / (dist1 * dist2); // denominator always > 0
3150 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3151 // Pointers are moving in the same direction. Switch to SWIPE.
3152#if DEBUG_GESTURES
3153 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3154 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3155 "cosine %0.3f >= %0.3f",
3156 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3157 mConfig.pointerGestureMultitouchMinDistance, cosine,
3158 mConfig.pointerGestureSwipeTransitionAngleCosine);
3159#endif
Michael Wright227c5542020-07-02 18:30:52 +01003160 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003161 } else {
3162 // Pointers are moving in different directions. Switch to FREEFORM.
3163#if DEBUG_GESTURES
3164 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3165 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3166 "cosine %0.3f < %0.3f",
3167 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3168 mConfig.pointerGestureMultitouchMinDistance, cosine,
3169 mConfig.pointerGestureSwipeTransitionAngleCosine);
3170#endif
3171 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003172 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003173 }
3174 }
3175 }
3176 }
3177 }
Michael Wright227c5542020-07-02 18:30:52 +01003178 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003179 // Switch from SWIPE to FREEFORM if additional pointers go down.
3180 // Cancel previous gesture.
3181 if (currentFingerCount > 2) {
3182#if DEBUG_GESTURES
3183 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3184 currentFingerCount);
3185#endif
3186 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003187 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003188 }
3189 }
3190
3191 // Move the reference points based on the overall group motion of the fingers
3192 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003193 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003194 (commonDeltaX || commonDeltaY)) {
3195 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3196 uint32_t id = idBits.clearFirstMarkedBit();
3197 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3198 delta.dx = 0;
3199 delta.dy = 0;
3200 }
3201
3202 mPointerGesture.referenceTouchX += commonDeltaX;
3203 mPointerGesture.referenceTouchY += commonDeltaY;
3204
3205 commonDeltaX *= mPointerXMovementScale;
3206 commonDeltaY *= mPointerYMovementScale;
3207
Prabir Pradhan1728b212021-10-19 16:00:03 -07003208 rotateDelta(mInputDeviceOrientation, &commonDeltaX, &commonDeltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003209 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3210
3211 mPointerGesture.referenceGestureX += commonDeltaX;
3212 mPointerGesture.referenceGestureY += commonDeltaY;
3213 }
3214
3215 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003216 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3217 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003218 // PRESS or SWIPE mode.
3219#if DEBUG_GESTURES
3220 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3221 "activeGestureId=%d, currentTouchPointerCount=%d",
3222 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3223#endif
3224 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3225
3226 mPointerGesture.currentGestureIdBits.clear();
3227 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3228 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3229 mPointerGesture.currentGestureProperties[0].clear();
3230 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3231 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3232 mPointerGesture.currentGestureCoords[0].clear();
3233 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3234 mPointerGesture.referenceGestureX);
3235 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3236 mPointerGesture.referenceGestureY);
3237 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003238 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003239 // FREEFORM mode.
3240#if DEBUG_GESTURES
3241 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3242 "activeGestureId=%d, currentTouchPointerCount=%d",
3243 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3244#endif
3245 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3246
3247 mPointerGesture.currentGestureIdBits.clear();
3248
3249 BitSet32 mappedTouchIdBits;
3250 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003251 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003252 // Initially, assign the active gesture id to the active touch point
3253 // if there is one. No other touch id bits are mapped yet.
3254 if (!*outCancelPreviousGesture) {
3255 mappedTouchIdBits.markBit(activeTouchId);
3256 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3257 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3258 mPointerGesture.activeGestureId;
3259 } else {
3260 mPointerGesture.activeGestureId = -1;
3261 }
3262 } else {
3263 // Otherwise, assume we mapped all touches from the previous frame.
3264 // Reuse all mappings that are still applicable.
3265 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3266 mCurrentCookedState.fingerIdBits.value;
3267 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3268
3269 // Check whether we need to choose a new active gesture id because the
3270 // current went went up.
3271 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3272 ~mCurrentCookedState.fingerIdBits.value);
3273 !upTouchIdBits.isEmpty();) {
3274 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3275 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3276 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3277 mPointerGesture.activeGestureId = -1;
3278 break;
3279 }
3280 }
3281 }
3282
3283#if DEBUG_GESTURES
3284 ALOGD("Gestures: FREEFORM follow up "
3285 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3286 "activeGestureId=%d",
3287 mappedTouchIdBits.value, usedGestureIdBits.value,
3288 mPointerGesture.activeGestureId);
3289#endif
3290
3291 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3292 for (uint32_t i = 0; i < currentFingerCount; i++) {
3293 uint32_t touchId = idBits.clearFirstMarkedBit();
3294 uint32_t gestureId;
3295 if (!mappedTouchIdBits.hasBit(touchId)) {
3296 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3297 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3298#if DEBUG_GESTURES
3299 ALOGD("Gestures: FREEFORM "
3300 "new mapping for touch id %d -> gesture id %d",
3301 touchId, gestureId);
3302#endif
3303 } else {
3304 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3305#if DEBUG_GESTURES
3306 ALOGD("Gestures: FREEFORM "
3307 "existing mapping for touch id %d -> gesture id %d",
3308 touchId, gestureId);
3309#endif
3310 }
3311 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3312 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3313
3314 const RawPointerData::Pointer& pointer =
3315 mCurrentRawState.rawPointerData.pointerForId(touchId);
3316 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3317 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
Prabir Pradhan1728b212021-10-19 16:00:03 -07003318 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003319
3320 mPointerGesture.currentGestureProperties[i].clear();
3321 mPointerGesture.currentGestureProperties[i].id = gestureId;
3322 mPointerGesture.currentGestureProperties[i].toolType =
3323 AMOTION_EVENT_TOOL_TYPE_FINGER;
3324 mPointerGesture.currentGestureCoords[i].clear();
3325 mPointerGesture.currentGestureCoords[i]
3326 .setAxisValue(AMOTION_EVENT_AXIS_X,
3327 mPointerGesture.referenceGestureX + deltaX);
3328 mPointerGesture.currentGestureCoords[i]
3329 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3330 mPointerGesture.referenceGestureY + deltaY);
3331 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3332 1.0f);
3333 }
3334
3335 if (mPointerGesture.activeGestureId < 0) {
3336 mPointerGesture.activeGestureId =
3337 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3338#if DEBUG_GESTURES
3339 ALOGD("Gestures: FREEFORM new "
3340 "activeGestureId=%d",
3341 mPointerGesture.activeGestureId);
3342#endif
3343 }
3344 }
3345 }
3346
3347 mPointerController->setButtonState(mCurrentRawState.buttonState);
3348
3349#if DEBUG_GESTURES
3350 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3351 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3352 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3353 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3354 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3355 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3356 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3357 uint32_t id = idBits.clearFirstMarkedBit();
3358 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3359 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3360 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3361 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3362 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3363 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3364 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3365 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3366 }
3367 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3368 uint32_t id = idBits.clearFirstMarkedBit();
3369 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3370 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3371 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3372 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3373 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3374 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3375 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3376 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3377 }
3378#endif
3379 return true;
3380}
3381
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003382void TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003383 mPointerSimple.currentCoords.clear();
3384 mPointerSimple.currentProperties.clear();
3385
3386 bool down, hovering;
3387 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3388 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3389 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhand7482e72021-03-09 13:54:55 -08003390 setMouseCursorPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3391 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003392
3393 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3394 down = !hovering;
3395
Prabir Pradhand7482e72021-03-09 13:54:55 -08003396 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003397 mPointerSimple.currentCoords.copyFrom(
3398 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3399 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3400 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3401 mPointerSimple.currentProperties.id = 0;
3402 mPointerSimple.currentProperties.toolType =
3403 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3404 } else {
3405 down = false;
3406 hovering = false;
3407 }
3408
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003409 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003410}
3411
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003412void TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3413 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003414}
3415
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003416void TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003417 mPointerSimple.currentCoords.clear();
3418 mPointerSimple.currentProperties.clear();
3419
3420 bool down, hovering;
3421 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3422 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3423 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3424 float deltaX = 0, deltaY = 0;
3425 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3426 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3427 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3428 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3429 mPointerXMovementScale;
3430 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3431 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3432 mPointerYMovementScale;
3433
Prabir Pradhan1728b212021-10-19 16:00:03 -07003434 rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003435 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3436
Prabir Pradhand7482e72021-03-09 13:54:55 -08003437 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003438 } else {
3439 mPointerVelocityControl.reset();
3440 }
3441
3442 down = isPointerDown(mCurrentRawState.buttonState);
3443 hovering = !down;
3444
Prabir Pradhand7482e72021-03-09 13:54:55 -08003445 auto [x, y] = getMouseCursorPosition();
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 Vishniakou58ba3d12021-02-11 01:31:07 +00003462 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003463}
3464
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003465void TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3466 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003467
3468 mPointerVelocityControl.reset();
3469}
3470
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003471void TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3472 bool down, bool hovering) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003473 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003474
3475 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003476 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003477 mPointerController->clearSpots();
3478 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003479 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003480 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003481 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003482 }
Garfield Tan9514d782020-11-10 16:37:23 -08003483 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003484
Prabir Pradhand7482e72021-03-09 13:54:55 -08003485 auto [xCursorPosition, yCursorPosition] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003486
3487 if (mPointerSimple.down && !down) {
3488 mPointerSimple.down = false;
3489
3490 // Send up.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003491 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3492 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003493 mLastRawState.buttonState, MotionClassification::NONE,
3494 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3495 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3496 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3497 /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003498 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003499 }
3500
3501 if (mPointerSimple.hovering && !hovering) {
3502 mPointerSimple.hovering = false;
3503
3504 // Send hover exit.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003505 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3506 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3507 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003508 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3509 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3510 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3511 /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003512 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003513 }
3514
3515 if (down) {
3516 if (!mPointerSimple.down) {
3517 mPointerSimple.down = true;
3518 mPointerSimple.downTime = when;
3519
3520 // Send down.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003521 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003522 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3523 metaState, mCurrentRawState.buttonState,
3524 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3525 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3526 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3527 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003528 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003529 }
3530
3531 // Send move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003532 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3533 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003534 mCurrentRawState.buttonState, MotionClassification::NONE,
3535 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3536 &mPointerSimple.currentCoords, mOrientedXPrecision,
3537 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3538 mPointerSimple.downTime, /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003539 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003540 }
3541
3542 if (hovering) {
3543 if (!mPointerSimple.hovering) {
3544 mPointerSimple.hovering = true;
3545
3546 // Send hover enter.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003547 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003548 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3549 metaState, mCurrentRawState.buttonState,
3550 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3551 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3552 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3553 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003554 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003555 }
3556
3557 // Send hover move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003558 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3559 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3560 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003561 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3562 &mPointerSimple.currentCoords, mOrientedXPrecision,
3563 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3564 mPointerSimple.downTime, /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003565 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003566 }
3567
3568 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3569 float vscroll = mCurrentRawState.rawVScroll;
3570 float hscroll = mCurrentRawState.rawHScroll;
3571 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3572 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3573
3574 // Send scroll.
3575 PointerCoords pointerCoords;
3576 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3577 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3578 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3579
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003580 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3581 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003582 mCurrentRawState.buttonState, MotionClassification::NONE,
3583 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3584 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3585 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3586 /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003587 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003588 }
3589
3590 // Save state.
3591 if (down || hovering) {
3592 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3593 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3594 } else {
3595 mPointerSimple.reset();
3596 }
3597}
3598
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003599void TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003600 mPointerSimple.currentCoords.clear();
3601 mPointerSimple.currentProperties.clear();
3602
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003603 dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003604}
3605
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003606void TouchInputMapper::dispatchMotion(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3607 uint32_t source, int32_t action, int32_t actionButton,
3608 int32_t flags, int32_t metaState, int32_t buttonState,
3609 int32_t edgeFlags, const PointerProperties* properties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003610 const PointerCoords* coords, const uint32_t* idToIndex,
3611 BitSet32 idBits, int32_t changedId, float xPrecision,
3612 float yPrecision, nsecs_t downTime) {
3613 PointerCoords pointerCoords[MAX_POINTERS];
3614 PointerProperties pointerProperties[MAX_POINTERS];
3615 uint32_t pointerCount = 0;
3616 while (!idBits.isEmpty()) {
3617 uint32_t id = idBits.clearFirstMarkedBit();
3618 uint32_t index = idToIndex[id];
3619 pointerProperties[pointerCount].copyFrom(properties[index]);
3620 pointerCoords[pointerCount].copyFrom(coords[index]);
3621
3622 if (changedId >= 0 && id == uint32_t(changedId)) {
3623 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3624 }
3625
3626 pointerCount += 1;
3627 }
3628
3629 ALOG_ASSERT(pointerCount != 0);
3630
3631 if (changedId >= 0 && pointerCount == 1) {
3632 // Replace initial down and final up action.
3633 // We can compare the action without masking off the changed pointer index
3634 // because we know the index is 0.
3635 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3636 action = AMOTION_EVENT_ACTION_DOWN;
3637 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003638 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3639 action = AMOTION_EVENT_ACTION_CANCEL;
3640 } else {
3641 action = AMOTION_EVENT_ACTION_UP;
3642 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003643 } else {
3644 // Can't happen.
3645 ALOG_ASSERT(false);
3646 }
3647 }
3648 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3649 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003650 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08003651 auto [x, y] = getMouseCursorPosition();
3652 xCursorPosition = x;
3653 yCursorPosition = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003654 }
3655 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3656 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003657 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003658 std::for_each(frames.begin(), frames.end(),
Prabir Pradhan1728b212021-10-19 16:00:03 -07003659 [this](TouchVideoFrame& frame) { frame.rotate(this->mInputDeviceOrientation); });
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003660 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3661 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003662 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3663 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3664 downTime, std::move(frames));
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003665 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003666}
3667
3668bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3669 const PointerCoords* inCoords,
3670 const uint32_t* inIdToIndex,
3671 PointerProperties* outProperties,
3672 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3673 BitSet32 idBits) const {
3674 bool changed = false;
3675 while (!idBits.isEmpty()) {
3676 uint32_t id = idBits.clearFirstMarkedBit();
3677 uint32_t inIndex = inIdToIndex[id];
3678 uint32_t outIndex = outIdToIndex[id];
3679
3680 const PointerProperties& curInProperties = inProperties[inIndex];
3681 const PointerCoords& curInCoords = inCoords[inIndex];
3682 PointerProperties& curOutProperties = outProperties[outIndex];
3683 PointerCoords& curOutCoords = outCoords[outIndex];
3684
3685 if (curInProperties != curOutProperties) {
3686 curOutProperties.copyFrom(curInProperties);
3687 changed = true;
3688 }
3689
3690 if (curInCoords != curOutCoords) {
3691 curOutCoords.copyFrom(curInCoords);
3692 changed = true;
3693 }
3694 }
3695 return changed;
3696}
3697
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003698void TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3699 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3700 abortTouches(when, readTime, 0 /* policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003701}
3702
Prabir Pradhan1728b212021-10-19 16:00:03 -07003703// Transform input device coordinates to display panel coordinates.
3704void TouchInputMapper::rotateAndScale(float& x, float& y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003705 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3706 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3707
arthurhunga36b28e2020-12-29 20:28:15 +08003708 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3709 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3710
Prabir Pradhan1728b212021-10-19 16:00:03 -07003711 // Rotate to display coordinate.
Arthur Hung4197f6b2020-03-16 15:39:59 +08003712 // 0 - no swap and reverse.
3713 // 90 - swap x/y and reverse y.
3714 // 180 - reverse x, y.
3715 // 270 - swap x/y and reverse x.
Prabir Pradhan1728b212021-10-19 16:00:03 -07003716 switch (mInputDeviceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003717 case DISPLAY_ORIENTATION_0:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003718 x = xScaled;
3719 y = yScaled;
Arthur Hung4197f6b2020-03-16 15:39:59 +08003720 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003721 case DISPLAY_ORIENTATION_90:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003722 y = xScaledMax;
3723 x = yScaled;
Arthur Hung05de5772019-09-26 18:31:26 +08003724 break;
3725 case DISPLAY_ORIENTATION_180:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003726 x = xScaledMax;
3727 y = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003728 break;
3729 case DISPLAY_ORIENTATION_270:
Prabir Pradhan1728b212021-10-19 16:00:03 -07003730 y = xScaled;
3731 x = yScaledMax;
Arthur Hung05de5772019-09-26 18:31:26 +08003732 break;
3733 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003734 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003735 }
3736}
3737
Prabir Pradhan1728b212021-10-19 16:00:03 -07003738bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003739 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3740 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3741
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003742 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003743 xScaled >= mPhysicalLeft && xScaled <= (mPhysicalLeft + mPhysicalWidth) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003744 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00003745 yScaled >= mPhysicalTop && yScaled <= (mPhysicalTop + mPhysicalHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003746}
3747
3748const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3749 for (const VirtualKey& virtualKey : mVirtualKeys) {
3750#if DEBUG_VIRTUAL_KEYS
3751 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3752 "left=%d, top=%d, right=%d, bottom=%d",
3753 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3754 virtualKey.hitRight, virtualKey.hitBottom);
3755#endif
3756
3757 if (virtualKey.isHit(x, y)) {
3758 return &virtualKey;
3759 }
3760 }
3761
3762 return nullptr;
3763}
3764
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003765void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3766 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3767 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003768
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003769 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003770
3771 if (currentPointerCount == 0) {
3772 // No pointers to assign.
3773 return;
3774 }
3775
3776 if (lastPointerCount == 0) {
3777 // All pointers are new.
3778 for (uint32_t i = 0; i < currentPointerCount; i++) {
3779 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003780 current.rawPointerData.pointers[i].id = id;
3781 current.rawPointerData.idToIndex[id] = i;
3782 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003783 }
3784 return;
3785 }
3786
3787 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003788 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003789 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003790 uint32_t id = last.rawPointerData.pointers[0].id;
3791 current.rawPointerData.pointers[0].id = id;
3792 current.rawPointerData.idToIndex[id] = 0;
3793 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003794 return;
3795 }
3796
3797 // General case.
3798 // We build a heap of squared euclidean distances between current and last pointers
3799 // associated with the current and last pointer indices. Then, we find the best
3800 // match (by distance) for each current pointer.
3801 // The pointers must have the same tool type but it is possible for them to
3802 // transition from hovering to touching or vice-versa while retaining the same id.
3803 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3804
3805 uint32_t heapSize = 0;
3806 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3807 currentPointerIndex++) {
3808 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3809 lastPointerIndex++) {
3810 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003811 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003812 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003813 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003814 if (currentPointer.toolType == lastPointer.toolType) {
3815 int64_t deltaX = currentPointer.x - lastPointer.x;
3816 int64_t deltaY = currentPointer.y - lastPointer.y;
3817
3818 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3819
3820 // Insert new element into the heap (sift up).
3821 heap[heapSize].currentPointerIndex = currentPointerIndex;
3822 heap[heapSize].lastPointerIndex = lastPointerIndex;
3823 heap[heapSize].distance = distance;
3824 heapSize += 1;
3825 }
3826 }
3827 }
3828
3829 // Heapify
3830 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3831 startIndex -= 1;
3832 for (uint32_t parentIndex = startIndex;;) {
3833 uint32_t childIndex = parentIndex * 2 + 1;
3834 if (childIndex >= heapSize) {
3835 break;
3836 }
3837
3838 if (childIndex + 1 < heapSize &&
3839 heap[childIndex + 1].distance < heap[childIndex].distance) {
3840 childIndex += 1;
3841 }
3842
3843 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3844 break;
3845 }
3846
3847 swap(heap[parentIndex], heap[childIndex]);
3848 parentIndex = childIndex;
3849 }
3850 }
3851
3852#if DEBUG_POINTER_ASSIGNMENT
3853 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3854 for (size_t i = 0; i < heapSize; i++) {
3855 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3856 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3857 }
3858#endif
3859
3860 // Pull matches out by increasing order of distance.
3861 // To avoid reassigning pointers that have already been matched, the loop keeps track
3862 // of which last and current pointers have been matched using the matchedXXXBits variables.
3863 // It also tracks the used pointer id bits.
3864 BitSet32 matchedLastBits(0);
3865 BitSet32 matchedCurrentBits(0);
3866 BitSet32 usedIdBits(0);
3867 bool first = true;
3868 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3869 while (heapSize > 0) {
3870 if (first) {
3871 // The first time through the loop, we just consume the root element of
3872 // the heap (the one with smallest distance).
3873 first = false;
3874 } else {
3875 // Previous iterations consumed the root element of the heap.
3876 // Pop root element off of the heap (sift down).
3877 heap[0] = heap[heapSize];
3878 for (uint32_t parentIndex = 0;;) {
3879 uint32_t childIndex = parentIndex * 2 + 1;
3880 if (childIndex >= heapSize) {
3881 break;
3882 }
3883
3884 if (childIndex + 1 < heapSize &&
3885 heap[childIndex + 1].distance < heap[childIndex].distance) {
3886 childIndex += 1;
3887 }
3888
3889 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3890 break;
3891 }
3892
3893 swap(heap[parentIndex], heap[childIndex]);
3894 parentIndex = childIndex;
3895 }
3896
3897#if DEBUG_POINTER_ASSIGNMENT
3898 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003899 for (size_t j = 0; j < heapSize; j++) {
3900 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3901 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003902 }
3903#endif
3904 }
3905
3906 heapSize -= 1;
3907
3908 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3909 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3910
3911 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3912 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3913
3914 matchedCurrentBits.markBit(currentPointerIndex);
3915 matchedLastBits.markBit(lastPointerIndex);
3916
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003917 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3918 current.rawPointerData.pointers[currentPointerIndex].id = id;
3919 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3920 current.rawPointerData.markIdBit(id,
3921 current.rawPointerData.isHovering(
3922 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003923 usedIdBits.markBit(id);
3924
3925#if DEBUG_POINTER_ASSIGNMENT
3926 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3927 ", distance=%" PRIu64,
3928 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3929#endif
3930 break;
3931 }
3932 }
3933
3934 // Assign fresh ids to pointers that were not matched in the process.
3935 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3936 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3937 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3938
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003939 current.rawPointerData.pointers[currentPointerIndex].id = id;
3940 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3941 current.rawPointerData.markIdBit(id,
3942 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003943
3944#if DEBUG_POINTER_ASSIGNMENT
3945 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3946#endif
3947 }
3948}
3949
3950int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3951 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3952 return AKEY_STATE_VIRTUAL;
3953 }
3954
3955 for (const VirtualKey& virtualKey : mVirtualKeys) {
3956 if (virtualKey.keyCode == keyCode) {
3957 return AKEY_STATE_UP;
3958 }
3959 }
3960
3961 return AKEY_STATE_UNKNOWN;
3962}
3963
3964int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3965 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3966 return AKEY_STATE_VIRTUAL;
3967 }
3968
3969 for (const VirtualKey& virtualKey : mVirtualKeys) {
3970 if (virtualKey.scanCode == scanCode) {
3971 return AKEY_STATE_UP;
3972 }
3973 }
3974
3975 return AKEY_STATE_UNKNOWN;
3976}
3977
3978bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3979 const int32_t* keyCodes, uint8_t* outFlags) {
3980 for (const VirtualKey& virtualKey : mVirtualKeys) {
3981 for (size_t i = 0; i < numCodes; i++) {
3982 if (virtualKey.keyCode == keyCodes[i]) {
3983 outFlags[i] = 1;
3984 }
3985 }
3986 }
3987
3988 return true;
3989}
3990
3991std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3992 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01003993 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003994 return std::make_optional(mPointerController->getDisplayId());
3995 } else {
3996 return std::make_optional(mViewport.displayId);
3997 }
3998 }
3999 return std::nullopt;
4000}
4001
Prabir Pradhand7482e72021-03-09 13:54:55 -08004002void TouchInputMapper::moveMouseCursor(float dx, float dy) const {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004003 // Convert from InputReader's un-rotated coordinate space to PointerController's coordinate
4004 // space that is oriented with the viewport.
4005 rotateDelta(mViewport.orientation, &dx, &dy);
Prabir Pradhand7482e72021-03-09 13:54:55 -08004006
4007 mPointerController->move(dx, dy);
4008}
4009
4010std::pair<float, float> TouchInputMapper::getMouseCursorPosition() const {
4011 float x = 0;
4012 float y = 0;
4013 mPointerController->getPosition(&x, &y);
4014
Prabir Pradhand7482e72021-03-09 13:54:55 -08004015 if (!mViewport.isValid()) return {x, y};
4016
4017 // Convert from PointerController's rotated coordinate space that is oriented with the viewport
4018 // to InputReader's un-rotated coordinate space.
4019 const int32_t orientation = getInverseRotation(mViewport.orientation);
4020 rotatePoint(orientation, x, y, mViewport.deviceWidth, mViewport.deviceHeight);
4021 return {x, y};
4022}
4023
4024void TouchInputMapper::setMouseCursorPosition(float x, float y) const {
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004025 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4026 // coordinate space that is oriented with the viewport.
Prabir Pradhan1728b212021-10-19 16:00:03 -07004027 rotatePoint(mViewport.orientation, x, y, mDisplayWidth, mDisplayHeight);
Prabir Pradhand7482e72021-03-09 13:54:55 -08004028
4029 mPointerController->setPosition(x, y);
4030}
4031
4032void TouchInputMapper::setTouchSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex,
4033 BitSet32 spotIdBits, int32_t displayId) {
4034 std::array<PointerCoords, MAX_POINTERS> outSpotCoords{};
4035
4036 for (BitSet32 idBits(spotIdBits); !idBits.isEmpty();) {
4037 const uint32_t index = spotIdToIndex[idBits.clearFirstMarkedBit()];
4038 float x = spotCoords[index].getX();
4039 float y = spotCoords[index].getY();
4040 float pressure = spotCoords[index].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4041
Prabir Pradhan8b89c2f2021-07-29 16:30:14 +00004042 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4043 // coordinate space.
Prabir Pradhan1728b212021-10-19 16:00:03 -07004044 rotatePoint(mViewport.orientation, x, y, mDisplayWidth, mDisplayHeight);
Prabir Pradhand7482e72021-03-09 13:54:55 -08004045
4046 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4047 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4048 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4049 }
4050
4051 mPointerController->setSpots(outSpotCoords.data(), spotIdToIndex, spotIdBits, displayId);
4052}
4053
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004054} // namespace android