blob: 419b0d0eed06a082b5c8d2ffd8b0a8c5d08ec890 [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),
Arthur Hung4197f6b2020-03-16 15:39:59 +0800171 mRawSurfaceWidth(-1),
172 mRawSurfaceHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700173 mSurfaceLeft(0),
174 mSurfaceTop(0),
Chris Ye42b06822020-08-07 11:39:33 -0700175 mSurfaceRight(0),
176 mSurfaceBottom(0),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700177 mPhysicalWidth(-1),
178 mPhysicalHeight(-1),
179 mPhysicalLeft(0),
180 mPhysicalTop(0),
181 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
182
183TouchInputMapper::~TouchInputMapper() {}
184
185uint32_t TouchInputMapper::getSources() {
186 return mSource;
187}
188
189void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
190 InputMapper::populateDeviceInfo(info);
191
Michael Wright227c5542020-07-02 18:30:52 +0100192 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700193 info->addMotionRange(mOrientedRanges.x);
194 info->addMotionRange(mOrientedRanges.y);
195 info->addMotionRange(mOrientedRanges.pressure);
196
Chris Yef74dc422020-09-02 22:41:50 -0700197 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
Chris Ye8fa17282020-09-15 17:17:34 -0700198 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
199 //
200 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
201 // motion, i.e. the hardware dimensions, as the finger could move completely across the
202 // touchpad in one sample cycle.
Chris Yef74dc422020-09-02 22:41:50 -0700203 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
204 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
205 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat,
206 x.fuzz, x.resolution);
207 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat,
208 y.fuzz, y.resolution);
209 }
210
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700211 if (mOrientedRanges.haveSize) {
212 info->addMotionRange(mOrientedRanges.size);
213 }
214
215 if (mOrientedRanges.haveTouchSize) {
216 info->addMotionRange(mOrientedRanges.touchMajor);
217 info->addMotionRange(mOrientedRanges.touchMinor);
218 }
219
220 if (mOrientedRanges.haveToolSize) {
221 info->addMotionRange(mOrientedRanges.toolMajor);
222 info->addMotionRange(mOrientedRanges.toolMinor);
223 }
224
225 if (mOrientedRanges.haveOrientation) {
226 info->addMotionRange(mOrientedRanges.orientation);
227 }
228
229 if (mOrientedRanges.haveDistance) {
230 info->addMotionRange(mOrientedRanges.distance);
231 }
232
233 if (mOrientedRanges.haveTilt) {
234 info->addMotionRange(mOrientedRanges.tilt);
235 }
236
237 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
238 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
239 0.0f);
240 }
241 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
242 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
243 0.0f);
244 }
Michael Wright227c5542020-07-02 18:30:52 +0100245 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700246 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
247 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
248 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
249 x.fuzz, x.resolution);
250 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
251 y.fuzz, y.resolution);
252 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
253 x.fuzz, x.resolution);
254 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
255 y.fuzz, y.resolution);
256 }
257 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
258 }
259}
260
261void TouchInputMapper::dump(std::string& dump) {
Chris Yea03dd232020-09-08 19:21:09 -0700262 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n",
Dominik Laskowski75788452021-02-09 18:51:25 -0800263 ftl::enum_string(mDeviceMode).c_str());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700264 dumpParameters(dump);
265 dumpVirtualKeys(dump);
266 dumpRawPointerAxes(dump);
267 dumpCalibration(dump);
268 dumpAffineTransformation(dump);
269 dumpSurface(dump);
270
271 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
272 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
273 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
274 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
275 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
276 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
277 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
278 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
279 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
280 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
281 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
282 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
283 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
284 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
285 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
286 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
287 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
288
289 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
290 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
291 mLastRawState.rawPointerData.pointerCount);
292 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
293 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
294 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
295 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
296 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
297 "toolType=%d, isHovering=%s\n",
298 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
299 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
300 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
301 pointer.distance, pointer.toolType, toString(pointer.isHovering));
302 }
303
304 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
305 mLastCookedState.buttonState);
306 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
307 mLastCookedState.cookedPointerData.pointerCount);
308 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
309 const PointerProperties& pointerProperties =
310 mLastCookedState.cookedPointerData.pointerProperties[i];
311 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000312 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
313 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
314 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700315 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
316 "toolType=%d, isHovering=%s\n",
317 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +0000318 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
319 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700320 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
321 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
322 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
323 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
324 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
325 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
326 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
327 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
328 pointerProperties.toolType,
329 toString(mLastCookedState.cookedPointerData.isHovering(i)));
330 }
331
332 dump += INDENT3 "Stylus Fusion:\n";
333 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
334 toString(mExternalStylusConnected));
335 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
336 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
337 mExternalStylusFusionTimeout);
338 dump += INDENT3 "External Stylus State:\n";
339 dumpStylusState(dump, mExternalStylusState);
340
Michael Wright227c5542020-07-02 18:30:52 +0100341 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700342 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
343 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
344 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
345 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
346 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
347 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
348 }
349}
350
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700351void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
352 uint32_t changes) {
353 InputMapper::configure(when, config, changes);
354
355 mConfig = *config;
356
357 if (!changes) { // first time only
358 // Configure basic parameters.
359 configureParameters();
360
361 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800362 mCursorScrollAccumulator.configure(getDeviceContext());
363 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700364
365 // Configure absolute axis information.
366 configureRawPointerAxes();
367
368 // Prepare input device calibration.
369 parseCalibration();
370 resolveCalibration();
371 }
372
373 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
374 // Update location calibration to reflect current settings
375 updateAffineTransformation();
376 }
377
378 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
379 // Update pointer speed.
380 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
381 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
382 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
383 }
384
385 bool resetNeeded = false;
386 if (!changes ||
387 (changes &
388 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800389 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700390 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
391 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
392 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
393 // Configure device sources, surface dimensions, orientation and
394 // scaling factors.
395 configureSurface(when, &resetNeeded);
396 }
397
398 if (changes && resetNeeded) {
399 // Send reset, unless this is the first time the device has been configured,
400 // in which case the reader will call reset itself after all mappers are ready.
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +0000401 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
402 getListener()->notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700403 }
404}
405
406void TouchInputMapper::resolveExternalStylusPresence() {
407 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800408 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700409 mExternalStylusConnected = !devices.empty();
410
411 if (!mExternalStylusConnected) {
412 resetExternalStylus();
413 }
414}
415
416void TouchInputMapper::configureParameters() {
417 // Use the pointer presentation mode for devices that do not support distinct
418 // multitouch. The spot-based presentation relies on being able to accurately
419 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800420 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wright227c5542020-07-02 18:30:52 +0100421 ? Parameters::GestureMode::SINGLE_TOUCH
422 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700423
424 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800425 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
426 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700427 if (gestureModeString == "single-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100428 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700429 } else if (gestureModeString == "multi-touch") {
Michael Wright227c5542020-07-02 18:30:52 +0100430 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700431 } else if (gestureModeString != "default") {
432 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
433 }
434 }
435
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800436 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700437 // The device is a touch screen.
Michael Wright227c5542020-07-02 18:30:52 +0100438 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800439 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700440 // The device is a pointing device like a track pad.
Michael Wright227c5542020-07-02 18:30:52 +0100441 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800442 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
443 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700444 // The device is a cursor device with a touch pad attached.
445 // By default don't use the touch pad to move the pointer.
Michael Wright227c5542020-07-02 18:30:52 +0100446 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700447 } else {
448 // The device is a touch pad of unknown purpose.
Michael Wright227c5542020-07-02 18:30:52 +0100449 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700450 }
451
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800452 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700453
454 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800455 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
456 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700457 if (deviceTypeString == "touchScreen") {
Michael Wright227c5542020-07-02 18:30:52 +0100458 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700459 } else if (deviceTypeString == "touchPad") {
Michael Wright227c5542020-07-02 18:30:52 +0100460 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700461 } else if (deviceTypeString == "touchNavigation") {
Michael Wright227c5542020-07-02 18:30:52 +0100462 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700463 } else if (deviceTypeString == "pointer") {
Michael Wright227c5542020-07-02 18:30:52 +0100464 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700465 } else if (deviceTypeString != "default") {
466 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
467 }
468 }
469
Michael Wright227c5542020-07-02 18:30:52 +0100470 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800471 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
472 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700473
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700474 mParameters.orientation = Parameters::Orientation::ORIENTATION_0;
475 String8 orientationString;
476 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientation"),
477 orientationString)) {
478 if (mParameters.deviceType != Parameters::DeviceType::TOUCH_SCREEN) {
479 ALOGW("The configuration 'touch.orientation' is only supported for touchscreens.");
480 } else if (orientationString == "ORIENTATION_90") {
481 mParameters.orientation = Parameters::Orientation::ORIENTATION_90;
482 } else if (orientationString == "ORIENTATION_180") {
483 mParameters.orientation = Parameters::Orientation::ORIENTATION_180;
484 } else if (orientationString == "ORIENTATION_270") {
485 mParameters.orientation = Parameters::Orientation::ORIENTATION_270;
486 } else if (orientationString != "ORIENTATION_0") {
487 ALOGW("Invalid value for touch.orientation: '%s'", orientationString.string());
488 }
489 }
490
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700491 mParameters.hasAssociatedDisplay = false;
492 mParameters.associatedDisplayIsExternal = false;
493 if (mParameters.orientationAware ||
Michael Wright227c5542020-07-02 18:30:52 +0100494 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
495 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700496 mParameters.hasAssociatedDisplay = true;
Michael Wright227c5542020-07-02 18:30:52 +0100497 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800498 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700499 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800500 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
501 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700502 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
503 }
504 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800505 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700506 mParameters.hasAssociatedDisplay = true;
507 }
508
509 // Initial downs on external touch devices should wake the device.
510 // Normally we don't do this for internal touch screens to prevent them from waking
511 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800512 mParameters.wake = getDeviceContext().isExternal();
513 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700514}
515
516void TouchInputMapper::dumpParameters(std::string& dump) {
517 dump += INDENT3 "Parameters:\n";
518
Dominik Laskowski75788452021-02-09 18:51:25 -0800519 dump += INDENT4 "GestureMode: " + ftl::enum_string(mParameters.gestureMode) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700520
Dominik Laskowski75788452021-02-09 18:51:25 -0800521 dump += INDENT4 "DeviceType: " + ftl::enum_string(mParameters.deviceType) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700522
523 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
524 "displayId='%s'\n",
525 toString(mParameters.hasAssociatedDisplay),
526 toString(mParameters.associatedDisplayIsExternal),
527 mParameters.uniqueDisplayId.c_str());
528 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
Dominik Laskowski75788452021-02-09 18:51:25 -0800529 dump += INDENT4 "Orientation: " + ftl::enum_string(mParameters.orientation) + "\n";
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700530}
531
532void TouchInputMapper::configureRawPointerAxes() {
533 mRawPointerAxes.clear();
534}
535
536void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
537 dump += INDENT3 "Raw Touch Axes:\n";
538 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
539 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
540 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
541 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
542 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
543 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
544 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
545 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
546 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
547 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
548 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
549 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
550 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
551}
552
553bool TouchInputMapper::hasExternalStylus() const {
554 return mExternalStylusConnected;
555}
556
557/**
558 * Determine which DisplayViewport to use.
559 * 1. If display port is specified, return the matching viewport. If matching viewport not
560 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800561 * 2. Always use the suggested viewport from WindowManagerService for pointers.
562 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700563 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800564 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700565 */
566std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewisd5665332018-02-22 13:31:42 -0800567 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800568 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700569 if (displayPort) {
570 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800571 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700572 }
573
Michael Wright227c5542020-07-02 18:30:52 +0100574 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800575 std::optional<DisplayViewport> viewport =
576 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
577 if (viewport) {
578 return viewport;
579 } else {
580 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
581 mConfig.defaultPointerDisplayId);
582 }
583 }
584
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700585 // Check if uniqueDisplayId is specified in idc file.
586 if (!mParameters.uniqueDisplayId.empty()) {
587 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
588 }
589
590 ViewportType viewportTypeToUse;
591 if (mParameters.associatedDisplayIsExternal) {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100592 viewportTypeToUse = ViewportType::EXTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700593 } else {
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100594 viewportTypeToUse = ViewportType::INTERNAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700595 }
596
597 std::optional<DisplayViewport> viewport =
598 mConfig.getDisplayViewportByType(viewportTypeToUse);
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100599 if (!viewport && viewportTypeToUse == ViewportType::EXTERNAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700600 ALOGW("Input device %s should be associated with external display, "
601 "fallback to internal one for the external viewport is not found.",
602 getDeviceName().c_str());
Michael Wrightfe3de7d2020-07-02 19:05:30 +0100603 viewport = mConfig.getDisplayViewportByType(ViewportType::INTERNAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700604 }
605
606 return viewport;
607 }
608
609 // No associated display, return a non-display viewport.
610 DisplayViewport newViewport;
611 // Raw width and height in the natural orientation.
612 int32_t rawWidth = mRawPointerAxes.getRawWidth();
613 int32_t rawHeight = mRawPointerAxes.getRawHeight();
614 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
615 return std::make_optional(newViewport);
616}
617
618void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wright227c5542020-07-02 18:30:52 +0100619 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700620
621 resolveExternalStylusPresence();
622
623 // Determine device mode.
Michael Wright227c5542020-07-02 18:30:52 +0100624 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000625 mConfig.pointerGesturesEnabled && !mConfig.pointerCaptureRequest.enable) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700626 mSource = AINPUT_SOURCE_MOUSE;
Michael Wright227c5542020-07-02 18:30:52 +0100627 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700628 if (hasStylus()) {
629 mSource |= AINPUT_SOURCE_STYLUS;
630 }
Garfield Tanc734e4f2021-01-15 20:01:39 -0800631 } else if (isTouchScreen()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700632 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wright227c5542020-07-02 18:30:52 +0100633 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700634 if (hasStylus()) {
635 mSource |= AINPUT_SOURCE_STYLUS;
636 }
637 if (hasExternalStylus()) {
638 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
639 }
Michael Wright227c5542020-07-02 18:30:52 +0100640 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700641 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wright227c5542020-07-02 18:30:52 +0100642 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700643 } else {
644 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wright227c5542020-07-02 18:30:52 +0100645 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700646 }
647
648 // Ensure we have valid X and Y axes.
649 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
650 ALOGW("Touch device '%s' did not report support for X or Y axis! "
651 "The device will be inoperable.",
652 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100653 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700654 return;
655 }
656
657 // Get associated display dimensions.
658 std::optional<DisplayViewport> newViewport = findViewport();
659 if (!newViewport) {
660 ALOGI("Touch device '%s' could not query the properties of its associated "
661 "display. The device will be inoperable until the display size "
662 "becomes available.",
663 getDeviceName().c_str());
Michael Wright227c5542020-07-02 18:30:52 +0100664 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700665 return;
666 }
667
Siarhei Vishniakou6f778462020-12-09 23:39:07 +0000668 if (!newViewport->isActive) {
669 ALOGI("Disabling %s (device %i) because the associated viewport is not active",
670 getDeviceName().c_str(), getDeviceId());
671 mDeviceMode = DeviceMode::DISABLED;
672 return;
673 }
674
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700675 // Raw width and height in the natural orientation.
676 int32_t rawWidth = mRawPointerAxes.getRawWidth();
677 int32_t rawHeight = mRawPointerAxes.getRawHeight();
678
679 bool viewportChanged = mViewport != *newViewport;
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700680 bool skipViewportUpdate = false;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700681 if (viewportChanged) {
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700682 bool viewportOrientationChanged = mViewport.orientation != newViewport->orientation;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700683 mViewport = *newViewport;
684
Michael Wright227c5542020-07-02 18:30:52 +0100685 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700686 // Convert rotated viewport to natural surface coordinates.
687 int32_t naturalLogicalWidth, naturalLogicalHeight;
688 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
689 int32_t naturalPhysicalLeft, naturalPhysicalTop;
690 int32_t naturalDeviceWidth, naturalDeviceHeight;
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700691
692 // Apply the inverse of the input device orientation so that the surface is configured
693 // in the same orientation as the device. The input device orientation will be
694 // re-applied to mSurfaceOrientation.
695 const int32_t naturalSurfaceOrientation =
696 (mViewport.orientation - static_cast<int32_t>(mParameters.orientation) + 4) % 4;
697 switch (naturalSurfaceOrientation) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700698 case DISPLAY_ORIENTATION_90:
699 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
700 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
701 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
702 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800703 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700704 naturalPhysicalTop = mViewport.physicalLeft;
705 naturalDeviceWidth = mViewport.deviceHeight;
706 naturalDeviceHeight = mViewport.deviceWidth;
707 break;
708 case DISPLAY_ORIENTATION_180:
709 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
710 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
711 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
712 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
713 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
714 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
715 naturalDeviceWidth = mViewport.deviceWidth;
716 naturalDeviceHeight = mViewport.deviceHeight;
717 break;
718 case DISPLAY_ORIENTATION_270:
719 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
720 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
721 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
722 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
723 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800724 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700725 naturalDeviceWidth = mViewport.deviceHeight;
726 naturalDeviceHeight = mViewport.deviceWidth;
727 break;
728 case DISPLAY_ORIENTATION_0:
729 default:
730 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
731 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
732 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
733 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
734 naturalPhysicalLeft = mViewport.physicalLeft;
735 naturalPhysicalTop = mViewport.physicalTop;
736 naturalDeviceWidth = mViewport.deviceWidth;
737 naturalDeviceHeight = mViewport.deviceHeight;
738 break;
739 }
740
741 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
742 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
743 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
744 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
745 }
746
747 mPhysicalWidth = naturalPhysicalWidth;
748 mPhysicalHeight = naturalPhysicalHeight;
749 mPhysicalLeft = naturalPhysicalLeft;
750 mPhysicalTop = naturalPhysicalTop;
751
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700752 const int32_t oldSurfaceWidth = mRawSurfaceWidth;
753 const int32_t oldSurfaceHeight = mRawSurfaceHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800754 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
755 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700756 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
757 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800758 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
759 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700760
Prabir Pradhand7482e72021-03-09 13:54:55 -0800761 if (isPerWindowInputRotationEnabled()) {
762 // When per-window input rotation is enabled, InputReader works in the un-rotated
763 // coordinate space, so we don't need to do anything if the device is already
764 // orientation-aware. If the device is not orientation-aware, then we need to apply
765 // the inverse rotation of the display so that when the display rotation is applied
766 // later as a part of the per-window transform, we get the expected screen
767 // coordinates.
768 mSurfaceOrientation = mParameters.orientationAware
769 ? DISPLAY_ORIENTATION_0
770 : getInverseRotation(mViewport.orientation);
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700771 // For orientation-aware devices that work in the un-rotated coordinate space, the
772 // viewport update should be skipped if it is only a change in the orientation.
773 skipViewportUpdate = mParameters.orientationAware &&
774 mRawSurfaceWidth == oldSurfaceWidth &&
775 mRawSurfaceHeight == oldSurfaceHeight && viewportOrientationChanged;
Prabir Pradhand7482e72021-03-09 13:54:55 -0800776 } else {
777 mSurfaceOrientation = mParameters.orientationAware ? mViewport.orientation
778 : DISPLAY_ORIENTATION_0;
779 }
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700780
781 // Apply the input device orientation for the device.
782 mSurfaceOrientation =
783 (mSurfaceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700784 } else {
785 mPhysicalWidth = rawWidth;
786 mPhysicalHeight = rawHeight;
787 mPhysicalLeft = 0;
788 mPhysicalTop = 0;
789
Arthur Hung4197f6b2020-03-16 15:39:59 +0800790 mRawSurfaceWidth = rawWidth;
791 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700792 mSurfaceLeft = 0;
793 mSurfaceTop = 0;
794 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
795 }
796 }
797
798 // If moving between pointer modes, need to reset some state.
799 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
800 if (deviceModeChanged) {
801 mOrientedRanges.clear();
802 }
803
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800804 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
805 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100806 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800807 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000808 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
809 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800810 if (mPointerController == nullptr) {
811 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700812 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000813 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800814 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
815 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700816 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100817 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700818 }
819
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700820 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700821 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
822 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800823 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700824 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
825
826 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800827 mXScale = float(mRawSurfaceWidth) / rawWidth;
828 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700829 mXTranslate = -mSurfaceLeft;
830 mYTranslate = -mSurfaceTop;
831 mXPrecision = 1.0f / mXScale;
832 mYPrecision = 1.0f / mYScale;
833
834 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
835 mOrientedRanges.x.source = mSource;
836 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
837 mOrientedRanges.y.source = mSource;
838
839 configureVirtualKeys();
840
841 // Scale factor for terms that are not oriented in a particular axis.
842 // If the pixels are square then xScale == yScale otherwise we fake it
843 // by choosing an average.
844 mGeometricScale = avg(mXScale, mYScale);
845
846 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800847 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700848
849 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100850 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700851 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
852 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
853 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
854 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
855 } else {
856 mSizeScale = 0.0f;
857 }
858
859 mOrientedRanges.haveTouchSize = true;
860 mOrientedRanges.haveToolSize = true;
861 mOrientedRanges.haveSize = true;
862
863 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
864 mOrientedRanges.touchMajor.source = mSource;
865 mOrientedRanges.touchMajor.min = 0;
866 mOrientedRanges.touchMajor.max = diagonalSize;
867 mOrientedRanges.touchMajor.flat = 0;
868 mOrientedRanges.touchMajor.fuzz = 0;
869 mOrientedRanges.touchMajor.resolution = 0;
870
871 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
872 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
873
874 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
875 mOrientedRanges.toolMajor.source = mSource;
876 mOrientedRanges.toolMajor.min = 0;
877 mOrientedRanges.toolMajor.max = diagonalSize;
878 mOrientedRanges.toolMajor.flat = 0;
879 mOrientedRanges.toolMajor.fuzz = 0;
880 mOrientedRanges.toolMajor.resolution = 0;
881
882 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
883 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
884
885 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
886 mOrientedRanges.size.source = mSource;
887 mOrientedRanges.size.min = 0;
888 mOrientedRanges.size.max = 1.0;
889 mOrientedRanges.size.flat = 0;
890 mOrientedRanges.size.fuzz = 0;
891 mOrientedRanges.size.resolution = 0;
892 } else {
893 mSizeScale = 0.0f;
894 }
895
896 // Pressure factors.
897 mPressureScale = 0;
898 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100899 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
900 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700901 if (mCalibration.havePressureScale) {
902 mPressureScale = mCalibration.pressureScale;
903 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
904 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
905 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
906 }
907 }
908
909 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
910 mOrientedRanges.pressure.source = mSource;
911 mOrientedRanges.pressure.min = 0;
912 mOrientedRanges.pressure.max = pressureMax;
913 mOrientedRanges.pressure.flat = 0;
914 mOrientedRanges.pressure.fuzz = 0;
915 mOrientedRanges.pressure.resolution = 0;
916
917 // Tilt
918 mTiltXCenter = 0;
919 mTiltXScale = 0;
920 mTiltYCenter = 0;
921 mTiltYScale = 0;
922 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
923 if (mHaveTilt) {
924 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
925 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
926 mTiltXScale = M_PI / 180;
927 mTiltYScale = M_PI / 180;
928
Tatsunosuke Tobita35e05532021-06-30 14:49:32 +0900929 if (mRawPointerAxes.tiltX.resolution) {
930 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
931 }
932 if (mRawPointerAxes.tiltY.resolution) {
933 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
934 }
935
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700936 mOrientedRanges.haveTilt = true;
937
938 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
939 mOrientedRanges.tilt.source = mSource;
940 mOrientedRanges.tilt.min = 0;
941 mOrientedRanges.tilt.max = M_PI_2;
942 mOrientedRanges.tilt.flat = 0;
943 mOrientedRanges.tilt.fuzz = 0;
944 mOrientedRanges.tilt.resolution = 0;
945 }
946
947 // Orientation
948 mOrientationScale = 0;
949 if (mHaveTilt) {
950 mOrientedRanges.haveOrientation = true;
951
952 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
953 mOrientedRanges.orientation.source = mSource;
954 mOrientedRanges.orientation.min = -M_PI;
955 mOrientedRanges.orientation.max = M_PI;
956 mOrientedRanges.orientation.flat = 0;
957 mOrientedRanges.orientation.fuzz = 0;
958 mOrientedRanges.orientation.resolution = 0;
959 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100960 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700961 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100962 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700963 if (mRawPointerAxes.orientation.valid) {
964 if (mRawPointerAxes.orientation.maxValue > 0) {
965 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
966 } else if (mRawPointerAxes.orientation.minValue < 0) {
967 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
968 } else {
969 mOrientationScale = 0;
970 }
971 }
972 }
973
974 mOrientedRanges.haveOrientation = true;
975
976 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
977 mOrientedRanges.orientation.source = mSource;
978 mOrientedRanges.orientation.min = -M_PI_2;
979 mOrientedRanges.orientation.max = M_PI_2;
980 mOrientedRanges.orientation.flat = 0;
981 mOrientedRanges.orientation.fuzz = 0;
982 mOrientedRanges.orientation.resolution = 0;
983 }
984
985 // Distance
986 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100987 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
988 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700989 if (mCalibration.haveDistanceScale) {
990 mDistanceScale = mCalibration.distanceScale;
991 } else {
992 mDistanceScale = 1.0f;
993 }
994 }
995
996 mOrientedRanges.haveDistance = true;
997
998 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
999 mOrientedRanges.distance.source = mSource;
1000 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
1001 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
1002 mOrientedRanges.distance.flat = 0;
1003 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
1004 mOrientedRanges.distance.resolution = 0;
1005 }
1006
1007 // Compute oriented precision, scales and ranges.
1008 // Note that the maximum value reported is an inclusive maximum value so it is one
1009 // unit less than the total width or height of surface.
1010 switch (mSurfaceOrientation) {
1011 case DISPLAY_ORIENTATION_90:
1012 case DISPLAY_ORIENTATION_270:
1013 mOrientedXPrecision = mYPrecision;
1014 mOrientedYPrecision = mXPrecision;
1015
1016 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001017 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001018 mOrientedRanges.x.flat = 0;
1019 mOrientedRanges.x.fuzz = 0;
1020 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
1021
1022 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001023 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001024 mOrientedRanges.y.flat = 0;
1025 mOrientedRanges.y.fuzz = 0;
1026 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
1027 break;
1028
1029 default:
1030 mOrientedXPrecision = mXPrecision;
1031 mOrientedYPrecision = mYPrecision;
1032
1033 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001034 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001035 mOrientedRanges.x.flat = 0;
1036 mOrientedRanges.x.fuzz = 0;
1037 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1038
1039 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001040 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001041 mOrientedRanges.y.flat = 0;
1042 mOrientedRanges.y.fuzz = 0;
1043 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1044 break;
1045 }
1046
1047 // Location
1048 updateAffineTransformation();
1049
Michael Wright227c5542020-07-02 18:30:52 +01001050 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001051 // Compute pointer gesture detection parameters.
1052 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001053 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001054
1055 // Scale movements such that one whole swipe of the touch pad covers a
1056 // given area relative to the diagonal size of the display when no acceleration
1057 // is applied.
1058 // Assume that the touch pad has a square aspect ratio such that movements in
1059 // X and Y of the same number of raw units cover the same physical distance.
1060 mPointerXMovementScale =
1061 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1062 mPointerYMovementScale = mPointerXMovementScale;
1063
1064 // Scale zooms to cover a smaller range of the display than movements do.
1065 // This value determines the area around the pointer that is affected by freeform
1066 // pointer gestures.
1067 mPointerXZoomScale =
1068 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1069 mPointerYZoomScale = mPointerXZoomScale;
1070
1071 // Max width between pointers to detect a swipe gesture is more than some fraction
1072 // of the diagonal axis of the touch pad. Touches that are wider than this are
1073 // translated into freeform gestures.
1074 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1075
1076 // Abort current pointer usages because the state has changed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001077 const nsecs_t readTime = when; // synthetic event
1078 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001079 }
1080
1081 // Inform the dispatcher about the changes.
1082 *outResetNeeded = true;
1083 bumpGeneration();
1084 }
1085}
1086
1087void TouchInputMapper::dumpSurface(std::string& dump) {
1088 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001089 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1090 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001091 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1092 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001093 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1094 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001095 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1096 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1097 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1098 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1099 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1100}
1101
1102void TouchInputMapper::configureVirtualKeys() {
1103 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001104 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001105
1106 mVirtualKeys.clear();
1107
1108 if (virtualKeyDefinitions.size() == 0) {
1109 return;
1110 }
1111
1112 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1113 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1114 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1115 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1116
1117 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1118 VirtualKey virtualKey;
1119
1120 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1121 int32_t keyCode;
1122 int32_t dummyKeyMetaState;
1123 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001124 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1125 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001126 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1127 continue; // drop the key
1128 }
1129
1130 virtualKey.keyCode = keyCode;
1131 virtualKey.flags = flags;
1132
1133 // convert the key definition's display coordinates into touch coordinates for a hit box
1134 int32_t halfWidth = virtualKeyDefinition.width / 2;
1135 int32_t halfHeight = virtualKeyDefinition.height / 2;
1136
1137 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001138 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001139 touchScreenLeft;
1140 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001141 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001142 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001143 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1144 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001145 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001146 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1147 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001148 touchScreenTop;
1149 mVirtualKeys.push_back(virtualKey);
1150 }
1151}
1152
1153void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1154 if (!mVirtualKeys.empty()) {
1155 dump += INDENT3 "Virtual Keys:\n";
1156
1157 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1158 const VirtualKey& virtualKey = mVirtualKeys[i];
1159 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1160 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1161 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1162 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1163 }
1164 }
1165}
1166
1167void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001168 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001169 Calibration& out = mCalibration;
1170
1171 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001172 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001173 String8 sizeCalibrationString;
1174 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1175 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001176 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001177 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001178 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001179 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001180 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001181 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001182 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001183 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001184 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001185 } else if (sizeCalibrationString != "default") {
1186 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1187 }
1188 }
1189
1190 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1191 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1192 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1193
1194 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001195 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001196 String8 pressureCalibrationString;
1197 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1198 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001199 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001200 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001201 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001202 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001203 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001204 } else if (pressureCalibrationString != "default") {
1205 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1206 pressureCalibrationString.string());
1207 }
1208 }
1209
1210 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1211
1212 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001213 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214 String8 orientationCalibrationString;
1215 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1216 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001217 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001218 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001219 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001220 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001221 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001222 } else if (orientationCalibrationString != "default") {
1223 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1224 orientationCalibrationString.string());
1225 }
1226 }
1227
1228 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001229 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001230 String8 distanceCalibrationString;
1231 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1232 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001233 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001234 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001235 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001236 } else if (distanceCalibrationString != "default") {
1237 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1238 distanceCalibrationString.string());
1239 }
1240 }
1241
1242 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1243
Michael Wright227c5542020-07-02 18:30:52 +01001244 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001245 String8 coverageCalibrationString;
1246 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1247 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001248 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001249 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001250 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001251 } else if (coverageCalibrationString != "default") {
1252 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1253 coverageCalibrationString.string());
1254 }
1255 }
1256}
1257
1258void TouchInputMapper::resolveCalibration() {
1259 // Size
1260 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001261 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1262 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001263 }
1264 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001265 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001266 }
1267
1268 // Pressure
1269 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001270 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1271 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001272 }
1273 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001274 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001275 }
1276
1277 // Orientation
1278 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001279 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1280 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281 }
1282 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001283 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284 }
1285
1286 // Distance
1287 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001288 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1289 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001290 }
1291 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001292 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001293 }
1294
1295 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001296 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1297 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001298 }
1299}
1300
1301void TouchInputMapper::dumpCalibration(std::string& dump) {
1302 dump += INDENT3 "Calibration:\n";
1303
1304 // Size
1305 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001306 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 dump += INDENT4 "touch.size.calibration: none\n";
1308 break;
Michael Wright227c5542020-07-02 18:30:52 +01001309 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001310 dump += INDENT4 "touch.size.calibration: geometric\n";
1311 break;
Michael Wright227c5542020-07-02 18:30:52 +01001312 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001313 dump += INDENT4 "touch.size.calibration: diameter\n";
1314 break;
Michael Wright227c5542020-07-02 18:30:52 +01001315 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001316 dump += INDENT4 "touch.size.calibration: box\n";
1317 break;
Michael Wright227c5542020-07-02 18:30:52 +01001318 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001319 dump += INDENT4 "touch.size.calibration: area\n";
1320 break;
1321 default:
1322 ALOG_ASSERT(false);
1323 }
1324
1325 if (mCalibration.haveSizeScale) {
1326 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1327 }
1328
1329 if (mCalibration.haveSizeBias) {
1330 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1331 }
1332
1333 if (mCalibration.haveSizeIsSummed) {
1334 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1335 toString(mCalibration.sizeIsSummed));
1336 }
1337
1338 // Pressure
1339 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001340 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001341 dump += INDENT4 "touch.pressure.calibration: none\n";
1342 break;
Michael Wright227c5542020-07-02 18:30:52 +01001343 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001344 dump += INDENT4 "touch.pressure.calibration: physical\n";
1345 break;
Michael Wright227c5542020-07-02 18:30:52 +01001346 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001347 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1348 break;
1349 default:
1350 ALOG_ASSERT(false);
1351 }
1352
1353 if (mCalibration.havePressureScale) {
1354 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1355 }
1356
1357 // Orientation
1358 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001359 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001360 dump += INDENT4 "touch.orientation.calibration: none\n";
1361 break;
Michael Wright227c5542020-07-02 18:30:52 +01001362 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001363 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1364 break;
Michael Wright227c5542020-07-02 18:30:52 +01001365 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001366 dump += INDENT4 "touch.orientation.calibration: vector\n";
1367 break;
1368 default:
1369 ALOG_ASSERT(false);
1370 }
1371
1372 // Distance
1373 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001374 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001375 dump += INDENT4 "touch.distance.calibration: none\n";
1376 break;
Michael Wright227c5542020-07-02 18:30:52 +01001377 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001378 dump += INDENT4 "touch.distance.calibration: scaled\n";
1379 break;
1380 default:
1381 ALOG_ASSERT(false);
1382 }
1383
1384 if (mCalibration.haveDistanceScale) {
1385 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1386 }
1387
1388 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001389 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001390 dump += INDENT4 "touch.coverage.calibration: none\n";
1391 break;
Michael Wright227c5542020-07-02 18:30:52 +01001392 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001393 dump += INDENT4 "touch.coverage.calibration: box\n";
1394 break;
1395 default:
1396 ALOG_ASSERT(false);
1397 }
1398}
1399
1400void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1401 dump += INDENT3 "Affine Transformation:\n";
1402
1403 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1404 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1405 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1406 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1407 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1408 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1409}
1410
1411void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001412 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001413 mSurfaceOrientation);
1414}
1415
1416void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001417 mCursorButtonAccumulator.reset(getDeviceContext());
1418 mCursorScrollAccumulator.reset(getDeviceContext());
1419 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001420
1421 mPointerVelocityControl.reset();
1422 mWheelXVelocityControl.reset();
1423 mWheelYVelocityControl.reset();
1424
1425 mRawStatesPending.clear();
1426 mCurrentRawState.clear();
1427 mCurrentCookedState.clear();
1428 mLastRawState.clear();
1429 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001430 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001431 mSentHoverEnter = false;
1432 mHavePointerIds = false;
1433 mCurrentMotionAborted = false;
1434 mDownTime = 0;
1435
1436 mCurrentVirtualKey.down = false;
1437
1438 mPointerGesture.reset();
1439 mPointerSimple.reset();
1440 resetExternalStylus();
1441
1442 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001443 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001444 mPointerController->clearSpots();
1445 }
1446
1447 InputMapper::reset(when);
1448}
1449
1450void TouchInputMapper::resetExternalStylus() {
1451 mExternalStylusState.clear();
1452 mExternalStylusId = -1;
1453 mExternalStylusFusionTimeout = LLONG_MAX;
1454 mExternalStylusDataPending = false;
1455}
1456
1457void TouchInputMapper::clearStylusDataPendingFlags() {
1458 mExternalStylusDataPending = false;
1459 mExternalStylusFusionTimeout = LLONG_MAX;
1460}
1461
1462void TouchInputMapper::process(const RawEvent* rawEvent) {
1463 mCursorButtonAccumulator.process(rawEvent);
1464 mCursorScrollAccumulator.process(rawEvent);
1465 mTouchButtonAccumulator.process(rawEvent);
1466
1467 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001468 sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001469 }
1470}
1471
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001472void TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001473 // Push a new state.
1474 mRawStatesPending.emplace_back();
1475
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001476 RawState& next = mRawStatesPending.back();
1477 next.clear();
1478 next.when = when;
1479 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001480
1481 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001482 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001483 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1484
1485 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001486 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1487 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001488 mCursorScrollAccumulator.finishSync();
1489
1490 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001491 syncTouch(when, &next);
1492
1493 // The last RawState is the actually second to last, since we just added a new state
1494 const RawState& last =
1495 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001496
1497 // Assign pointer ids.
1498 if (!mHavePointerIds) {
1499 assignPointerIds(last, next);
1500 }
1501
1502#if DEBUG_RAW_EVENTS
1503 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001504 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001505 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1506 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1507 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1508 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001509#endif
1510
Arthur Hung9ad18942021-06-19 02:04:46 +00001511 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1512 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1513 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1514 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1515 next.rawPointerData.hoveringIdBits.value);
1516 }
1517
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001518 processRawTouches(false /*timeout*/);
1519}
1520
1521void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001522 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001523 // Drop all input if the device is disabled.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001524 cancelTouch(mCurrentRawState.when, mCurrentRawState.readTime);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001525 mCurrentCookedState.clear();
1526 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001527 return;
1528 }
1529
1530 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1531 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1532 // touching the current state will only observe the events that have been dispatched to the
1533 // rest of the pipeline.
1534 const size_t N = mRawStatesPending.size();
1535 size_t count;
1536 for (count = 0; count < N; count++) {
1537 const RawState& next = mRawStatesPending[count];
1538
1539 // A failure to assign the stylus id means that we're waiting on stylus data
1540 // and so should defer the rest of the pipeline.
1541 if (assignExternalStylusId(next, timeout)) {
1542 break;
1543 }
1544
1545 // All ready to go.
1546 clearStylusDataPendingFlags();
1547 mCurrentRawState.copyFrom(next);
1548 if (mCurrentRawState.when < mLastRawState.when) {
1549 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001550 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001551 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001552 cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001553 }
1554 if (count != 0) {
1555 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1556 }
1557
1558 if (mExternalStylusDataPending) {
1559 if (timeout) {
1560 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1561 clearStylusDataPendingFlags();
1562 mCurrentRawState.copyFrom(mLastRawState);
1563#if DEBUG_STYLUS_FUSION
1564 ALOGD("Timeout expired, synthesizing event with new stylus data");
1565#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001566 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
1567 cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001568 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1569 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1570 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1571 }
1572 }
1573}
1574
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001575void TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001576 // Always start with a clean state.
1577 mCurrentCookedState.clear();
1578
1579 // Apply stylus buttons to current raw state.
1580 applyExternalStylusButtonState(when);
1581
1582 // Handle policy on initial down or hover events.
1583 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1584 mCurrentRawState.rawPointerData.pointerCount != 0;
1585
1586 uint32_t policyFlags = 0;
1587 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1588 if (initialDown || buttonsPressed) {
1589 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001590 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001591 getContext()->fadePointer();
1592 }
1593
1594 if (mParameters.wake) {
1595 policyFlags |= POLICY_FLAG_WAKE;
1596 }
1597 }
1598
1599 // Consume raw off-screen touches before cooking pointer data.
1600 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001601 if (consumeRawTouches(when, readTime, policyFlags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001602 mCurrentRawState.rawPointerData.clear();
1603 }
1604
1605 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1606 // with cooked pointer data that has the same ids and indices as the raw data.
1607 // The following code can use either the raw or cooked data, as needed.
1608 cookPointerData();
1609
1610 // Apply stylus pressure to current cooked state.
1611 applyExternalStylusTouchState(when);
1612
1613 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001614 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1615 mSource, mViewport.displayId, policyFlags, mLastCookedState.buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001616 mCurrentCookedState.buttonState);
1617
1618 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001619 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001620 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1621 uint32_t id = idBits.clearFirstMarkedBit();
1622 const RawPointerData::Pointer& pointer =
1623 mCurrentRawState.rawPointerData.pointerForId(id);
1624 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1625 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1626 mCurrentCookedState.stylusIdBits.markBit(id);
1627 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1628 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1629 mCurrentCookedState.fingerIdBits.markBit(id);
1630 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1631 mCurrentCookedState.mouseIdBits.markBit(id);
1632 }
1633 }
1634 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1635 uint32_t id = idBits.clearFirstMarkedBit();
1636 const RawPointerData::Pointer& pointer =
1637 mCurrentRawState.rawPointerData.pointerForId(id);
1638 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1639 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1640 mCurrentCookedState.stylusIdBits.markBit(id);
1641 }
1642 }
1643
1644 // Stylus takes precedence over all tools, then mouse, then finger.
1645 PointerUsage pointerUsage = mPointerUsage;
1646 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1647 mCurrentCookedState.mouseIdBits.clear();
1648 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001649 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001650 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1651 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001652 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001653 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1654 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001655 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001656 }
1657
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001658 dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001659 } else {
Garfield Tanc734e4f2021-01-15 20:01:39 -08001660 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001661
1662 if (!mCurrentMotionAborted) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001663 dispatchButtonRelease(when, readTime, policyFlags);
1664 dispatchHoverExit(when, readTime, policyFlags);
1665 dispatchTouches(when, readTime, policyFlags);
1666 dispatchHoverEnterAndMove(when, readTime, policyFlags);
1667 dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001668 }
1669
1670 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1671 mCurrentMotionAborted = false;
1672 }
1673 }
1674
1675 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001676 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001677 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1678 mCurrentCookedState.buttonState);
1679
1680 // Clear some transient state.
1681 mCurrentRawState.rawVScroll = 0;
1682 mCurrentRawState.rawHScroll = 0;
1683
1684 // Copy current touch to last touch in preparation for the next cycle.
1685 mLastRawState.copyFrom(mCurrentRawState);
1686 mLastCookedState.copyFrom(mCurrentCookedState);
1687}
1688
Garfield Tanc734e4f2021-01-15 20:01:39 -08001689void TouchInputMapper::updateTouchSpots() {
1690 if (!mConfig.showTouches || mPointerController == nullptr) {
1691 return;
1692 }
1693
1694 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1695 // clear touch spots.
1696 if (mDeviceMode != DeviceMode::DIRECT &&
1697 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1698 return;
1699 }
1700
1701 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1702 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1703
1704 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand7482e72021-03-09 13:54:55 -08001705 setTouchSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1706 mCurrentCookedState.cookedPointerData.idToIndex,
1707 mCurrentCookedState.cookedPointerData.touchingIdBits, mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001708}
1709
1710bool TouchInputMapper::isTouchScreen() {
1711 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1712 mParameters.hasAssociatedDisplay;
1713}
1714
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001715void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001716 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001717 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1718 }
1719}
1720
1721void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1722 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1723 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1724
1725 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1726 float pressure = mExternalStylusState.pressure;
1727 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1728 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1729 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1730 }
1731 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1732 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1733
1734 PointerProperties& properties =
1735 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1736 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1737 properties.toolType = mExternalStylusState.toolType;
1738 }
1739 }
1740}
1741
1742bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001743 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001744 return false;
1745 }
1746
1747 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1748 state.rawPointerData.pointerCount != 0;
1749 if (initialDown) {
1750 if (mExternalStylusState.pressure != 0.0f) {
1751#if DEBUG_STYLUS_FUSION
1752 ALOGD("Have both stylus and touch data, beginning fusion");
1753#endif
1754 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1755 } else if (timeout) {
1756#if DEBUG_STYLUS_FUSION
1757 ALOGD("Timeout expired, assuming touch is not a stylus.");
1758#endif
1759 resetExternalStylus();
1760 } else {
1761 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1762 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1763 }
1764#if DEBUG_STYLUS_FUSION
1765 ALOGD("No stylus data but stylus is connected, requesting timeout "
1766 "(%" PRId64 "ms)",
1767 mExternalStylusFusionTimeout);
1768#endif
1769 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1770 return true;
1771 }
1772 }
1773
1774 // Check if the stylus pointer has gone up.
1775 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1776#if DEBUG_STYLUS_FUSION
1777 ALOGD("Stylus pointer is going up");
1778#endif
1779 mExternalStylusId = -1;
1780 }
1781
1782 return false;
1783}
1784
1785void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001786 if (mDeviceMode == DeviceMode::POINTER) {
1787 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001788 // Since this is a synthetic event, we can consider its latency to be zero
1789 const nsecs_t readTime = when;
1790 dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001791 }
Michael Wright227c5542020-07-02 18:30:52 +01001792 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001793 if (mExternalStylusFusionTimeout < when) {
1794 processRawTouches(true /*timeout*/);
1795 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1796 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1797 }
1798 }
1799}
1800
1801void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1802 mExternalStylusState.copyFrom(state);
1803 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1804 // We're either in the middle of a fused stream of data or we're waiting on data before
1805 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1806 // data.
1807 mExternalStylusDataPending = true;
1808 processRawTouches(false /*timeout*/);
1809 }
1810}
1811
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001812bool TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001813 // Check for release of a virtual key.
1814 if (mCurrentVirtualKey.down) {
1815 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1816 // Pointer went up while virtual key was down.
1817 mCurrentVirtualKey.down = false;
1818 if (!mCurrentVirtualKey.ignored) {
1819#if DEBUG_VIRTUAL_KEYS
1820 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1821 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1822#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001823 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001824 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1825 }
1826 return true;
1827 }
1828
1829 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1830 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1831 const RawPointerData::Pointer& pointer =
1832 mCurrentRawState.rawPointerData.pointerForId(id);
1833 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1834 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1835 // Pointer is still within the space of the virtual key.
1836 return true;
1837 }
1838 }
1839
1840 // Pointer left virtual key area or another pointer also went down.
1841 // Send key cancellation but do not consume the touch yet.
1842 // This is useful when the user swipes through from the virtual key area
1843 // into the main display surface.
1844 mCurrentVirtualKey.down = false;
1845 if (!mCurrentVirtualKey.ignored) {
1846#if DEBUG_VIRTUAL_KEYS
1847 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1848 mCurrentVirtualKey.scanCode);
1849#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001850 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001851 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1852 AKEY_EVENT_FLAG_CANCELED);
1853 }
1854 }
1855
1856 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1857 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1858 // Pointer just went down. Check for virtual key press or off-screen touches.
1859 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1860 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001861 // Exclude unscaled device for inside surface checking.
1862 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001863 // If exactly one pointer went down, check for virtual key hit.
1864 // Otherwise we will drop the entire stroke.
1865 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1866 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1867 if (virtualKey) {
1868 mCurrentVirtualKey.down = true;
1869 mCurrentVirtualKey.downTime = when;
1870 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1871 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1872 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001873 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1874 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001875
1876 if (!mCurrentVirtualKey.ignored) {
1877#if DEBUG_VIRTUAL_KEYS
1878 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1879 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1880#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001881 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_DOWN,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001882 AKEY_EVENT_FLAG_FROM_SYSTEM |
1883 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1884 }
1885 }
1886 }
1887 return true;
1888 }
1889 }
1890
1891 // Disable all virtual key touches that happen within a short time interval of the
1892 // most recent touch within the screen area. The idea is to filter out stray
1893 // virtual key presses when interacting with the touch screen.
1894 //
1895 // Problems we're trying to solve:
1896 //
1897 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1898 // virtual key area that is implemented by a separate touch panel and accidentally
1899 // triggers a virtual key.
1900 //
1901 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1902 // area and accidentally triggers a virtual key. This often happens when virtual keys
1903 // are layed out below the screen near to where the on screen keyboard's space bar
1904 // is displayed.
1905 if (mConfig.virtualKeyQuietTime > 0 &&
1906 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001907 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001908 }
1909 return false;
1910}
1911
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001912void TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001913 int32_t keyEventAction, int32_t keyEventFlags) {
1914 int32_t keyCode = mCurrentVirtualKey.keyCode;
1915 int32_t scanCode = mCurrentVirtualKey.scanCode;
1916 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001917 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001918 policyFlags |= POLICY_FLAG_VIRTUAL;
1919
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001920 NotifyKeyArgs args(getContext()->getNextId(), when, readTime, getDeviceId(),
1921 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1922 keyEventFlags, keyCode, scanCode, metaState, downTime);
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00001923 getListener()->notifyKey(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001924}
1925
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001926void TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001927 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1928 if (!currentIdBits.isEmpty()) {
1929 int32_t metaState = getContext()->getGlobalMetaState();
1930 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001931 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
1932 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001933 mCurrentCookedState.cookedPointerData.pointerProperties,
1934 mCurrentCookedState.cookedPointerData.pointerCoords,
1935 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1936 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1937 mCurrentMotionAborted = true;
1938 }
1939}
1940
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001941void TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001942 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1943 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1944 int32_t metaState = getContext()->getGlobalMetaState();
1945 int32_t buttonState = mCurrentCookedState.buttonState;
1946
1947 if (currentIdBits == lastIdBits) {
1948 if (!currentIdBits.isEmpty()) {
1949 // No pointer id changes so this is a move event.
1950 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001951 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1952 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001953 mCurrentCookedState.cookedPointerData.pointerProperties,
1954 mCurrentCookedState.cookedPointerData.pointerCoords,
1955 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1956 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1957 }
1958 } else {
1959 // There may be pointers going up and pointers going down and pointers moving
1960 // all at the same time.
1961 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1962 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1963 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1964 BitSet32 dispatchedIdBits(lastIdBits.value);
1965
1966 // Update last coordinates of pointers that have moved so that we observe the new
1967 // pointer positions at the same time as other pointers that have just gone up.
1968 bool moveNeeded =
1969 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1970 mCurrentCookedState.cookedPointerData.pointerCoords,
1971 mCurrentCookedState.cookedPointerData.idToIndex,
1972 mLastCookedState.cookedPointerData.pointerProperties,
1973 mLastCookedState.cookedPointerData.pointerCoords,
1974 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1975 if (buttonState != mLastCookedState.buttonState) {
1976 moveNeeded = true;
1977 }
1978
1979 // Dispatch pointer up events.
1980 while (!upIdBits.isEmpty()) {
1981 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001982 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001983 if (isCanceled) {
1984 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1985 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001986 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
arthurhungcc7f9802020-04-30 17:55:40 +08001987 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001988 mLastCookedState.cookedPointerData.pointerProperties,
1989 mLastCookedState.cookedPointerData.pointerCoords,
1990 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1991 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1992 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08001993 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001994 }
1995
1996 // Dispatch move events if any of the remaining pointers moved from their old locations.
1997 // Although applications receive new locations as part of individual pointer up
1998 // events, they do not generally handle them except when presented in a move event.
1999 if (moveNeeded && !moveIdBits.isEmpty()) {
2000 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002001 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
2002 metaState, buttonState, 0,
2003 mCurrentCookedState.cookedPointerData.pointerProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002004 mCurrentCookedState.cookedPointerData.pointerCoords,
2005 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
2006 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2007 }
2008
2009 // Dispatch pointer down events using the new pointer locations.
2010 while (!downIdBits.isEmpty()) {
2011 uint32_t downId = downIdBits.clearFirstMarkedBit();
2012 dispatchedIdBits.markBit(downId);
2013
2014 if (dispatchedIdBits.count() == 1) {
2015 // First pointer is going down. Set down time.
2016 mDownTime = when;
2017 }
2018
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002019 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
2020 0, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002021 mCurrentCookedState.cookedPointerData.pointerProperties,
2022 mCurrentCookedState.cookedPointerData.pointerCoords,
2023 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
2024 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2025 }
2026 }
2027}
2028
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002029void TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002030 if (mSentHoverEnter &&
2031 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2032 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2033 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002034 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
2035 metaState, mLastCookedState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002036 mLastCookedState.cookedPointerData.pointerProperties,
2037 mLastCookedState.cookedPointerData.pointerCoords,
2038 mLastCookedState.cookedPointerData.idToIndex,
2039 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
2040 mOrientedYPrecision, mDownTime);
2041 mSentHoverEnter = false;
2042 }
2043}
2044
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002045void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2046 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002047 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2048 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2049 int32_t metaState = getContext()->getGlobalMetaState();
2050 if (!mSentHoverEnter) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002051 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
2052 0, 0, metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002053 mCurrentCookedState.cookedPointerData.pointerProperties,
2054 mCurrentCookedState.cookedPointerData.pointerCoords,
2055 mCurrentCookedState.cookedPointerData.idToIndex,
2056 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2057 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2058 mSentHoverEnter = true;
2059 }
2060
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002061 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2062 metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002063 mCurrentCookedState.cookedPointerData.pointerProperties,
2064 mCurrentCookedState.cookedPointerData.pointerCoords,
2065 mCurrentCookedState.cookedPointerData.idToIndex,
2066 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2067 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2068 }
2069}
2070
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002071void TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002072 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2073 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2074 const int32_t metaState = getContext()->getGlobalMetaState();
2075 int32_t buttonState = mLastCookedState.buttonState;
2076 while (!releasedButtons.isEmpty()) {
2077 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2078 buttonState &= ~actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002079 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002080 actionButton, 0, metaState, buttonState, 0,
2081 mCurrentCookedState.cookedPointerData.pointerProperties,
2082 mCurrentCookedState.cookedPointerData.pointerCoords,
2083 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2084 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2085 }
2086}
2087
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002088void TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002089 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2090 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2091 const int32_t metaState = getContext()->getGlobalMetaState();
2092 int32_t buttonState = mLastCookedState.buttonState;
2093 while (!pressedButtons.isEmpty()) {
2094 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2095 buttonState |= actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002096 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2097 actionButton, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002098 mCurrentCookedState.cookedPointerData.pointerProperties,
2099 mCurrentCookedState.cookedPointerData.pointerCoords,
2100 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2101 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2102 }
2103}
2104
2105const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2106 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2107 return cookedPointerData.touchingIdBits;
2108 }
2109 return cookedPointerData.hoveringIdBits;
2110}
2111
2112void TouchInputMapper::cookPointerData() {
2113 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2114
2115 mCurrentCookedState.cookedPointerData.clear();
2116 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2117 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2118 mCurrentRawState.rawPointerData.hoveringIdBits;
2119 mCurrentCookedState.cookedPointerData.touchingIdBits =
2120 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002121 mCurrentCookedState.cookedPointerData.canceledIdBits =
2122 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002123
2124 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2125 mCurrentCookedState.buttonState = 0;
2126 } else {
2127 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2128 }
2129
2130 // Walk through the the active pointers and map device coordinates onto
2131 // surface coordinates and adjust for display orientation.
2132 for (uint32_t i = 0; i < currentPointerCount; i++) {
2133 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2134
2135 // Size
2136 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2137 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002138 case Calibration::SizeCalibration::GEOMETRIC:
2139 case Calibration::SizeCalibration::DIAMETER:
2140 case Calibration::SizeCalibration::BOX:
2141 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002142 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2143 touchMajor = in.touchMajor;
2144 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2145 toolMajor = in.toolMajor;
2146 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2147 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2148 : in.touchMajor;
2149 } else if (mRawPointerAxes.touchMajor.valid) {
2150 toolMajor = touchMajor = in.touchMajor;
2151 toolMinor = touchMinor =
2152 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2153 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2154 : in.touchMajor;
2155 } else if (mRawPointerAxes.toolMajor.valid) {
2156 touchMajor = toolMajor = in.toolMajor;
2157 touchMinor = toolMinor =
2158 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2159 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2160 : in.toolMajor;
2161 } else {
2162 ALOG_ASSERT(false,
2163 "No touch or tool axes. "
2164 "Size calibration should have been resolved to NONE.");
2165 touchMajor = 0;
2166 touchMinor = 0;
2167 toolMajor = 0;
2168 toolMinor = 0;
2169 size = 0;
2170 }
2171
2172 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2173 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2174 if (touchingCount > 1) {
2175 touchMajor /= touchingCount;
2176 touchMinor /= touchingCount;
2177 toolMajor /= touchingCount;
2178 toolMinor /= touchingCount;
2179 size /= touchingCount;
2180 }
2181 }
2182
Michael Wright227c5542020-07-02 18:30:52 +01002183 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002184 touchMajor *= mGeometricScale;
2185 touchMinor *= mGeometricScale;
2186 toolMajor *= mGeometricScale;
2187 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002188 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002189 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2190 touchMinor = touchMajor;
2191 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2192 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002193 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002194 touchMinor = touchMajor;
2195 toolMinor = toolMajor;
2196 }
2197
2198 mCalibration.applySizeScaleAndBias(&touchMajor);
2199 mCalibration.applySizeScaleAndBias(&touchMinor);
2200 mCalibration.applySizeScaleAndBias(&toolMajor);
2201 mCalibration.applySizeScaleAndBias(&toolMinor);
2202 size *= mSizeScale;
2203 break;
2204 default:
2205 touchMajor = 0;
2206 touchMinor = 0;
2207 toolMajor = 0;
2208 toolMinor = 0;
2209 size = 0;
2210 break;
2211 }
2212
2213 // Pressure
2214 float pressure;
2215 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002216 case Calibration::PressureCalibration::PHYSICAL:
2217 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002218 pressure = in.pressure * mPressureScale;
2219 break;
2220 default:
2221 pressure = in.isHovering ? 0 : 1;
2222 break;
2223 }
2224
2225 // Tilt and Orientation
2226 float tilt;
2227 float orientation;
2228 if (mHaveTilt) {
2229 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2230 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2231 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2232 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2233 } else {
2234 tilt = 0;
2235
2236 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002237 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002238 orientation = in.orientation * mOrientationScale;
2239 break;
Michael Wright227c5542020-07-02 18:30:52 +01002240 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002241 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2242 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2243 if (c1 != 0 || c2 != 0) {
2244 orientation = atan2f(c1, c2) * 0.5f;
2245 float confidence = hypotf(c1, c2);
2246 float scale = 1.0f + confidence / 16.0f;
2247 touchMajor *= scale;
2248 touchMinor /= scale;
2249 toolMajor *= scale;
2250 toolMinor /= scale;
2251 } else {
2252 orientation = 0;
2253 }
2254 break;
2255 }
2256 default:
2257 orientation = 0;
2258 }
2259 }
2260
2261 // Distance
2262 float distance;
2263 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002264 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002265 distance = in.distance * mDistanceScale;
2266 break;
2267 default:
2268 distance = 0;
2269 }
2270
2271 // Coverage
2272 int32_t rawLeft, rawTop, rawRight, rawBottom;
2273 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002274 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002275 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2276 rawRight = in.toolMinor & 0x0000ffff;
2277 rawBottom = in.toolMajor & 0x0000ffff;
2278 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2279 break;
2280 default:
2281 rawLeft = rawTop = rawRight = rawBottom = 0;
2282 break;
2283 }
2284
2285 // Adjust X,Y coords for device calibration
2286 // TODO: Adjust coverage coords?
2287 float xTransformed = in.x, yTransformed = in.y;
2288 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002289 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002290
2291 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002292 float left, top, right, bottom;
2293
2294 switch (mSurfaceOrientation) {
2295 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002296 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2297 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2298 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2299 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2300 orientation -= M_PI_2;
2301 if (mOrientedRanges.haveOrientation &&
2302 orientation < mOrientedRanges.orientation.min) {
2303 orientation +=
2304 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2305 }
2306 break;
2307 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002308 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2309 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2310 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2311 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2312 orientation -= M_PI;
2313 if (mOrientedRanges.haveOrientation &&
2314 orientation < mOrientedRanges.orientation.min) {
2315 orientation +=
2316 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2317 }
2318 break;
2319 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002320 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2321 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2322 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2323 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2324 orientation += M_PI_2;
2325 if (mOrientedRanges.haveOrientation &&
2326 orientation > mOrientedRanges.orientation.max) {
2327 orientation -=
2328 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2329 }
2330 break;
2331 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002332 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2333 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2334 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2335 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2336 break;
2337 }
2338
2339 // Write output coords.
2340 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2341 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002342 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2343 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002344 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2345 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2346 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2347 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2348 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2349 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2350 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002351 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002352 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2353 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2354 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2355 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2356 } else {
2357 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2358 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2359 }
2360
Chris Ye364fdb52020-08-05 15:07:56 -07002361 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002362 uint32_t id = in.id;
2363 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2364 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2365 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2366 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2367 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2368 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2369 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2370 }
2371
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002372 // Write output properties.
2373 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002374 properties.clear();
2375 properties.id = id;
2376 properties.toolType = in.toolType;
2377
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002378 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002379 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002380 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002381 }
2382}
2383
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002384void TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002385 PointerUsage pointerUsage) {
2386 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002387 abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002388 mPointerUsage = pointerUsage;
2389 }
2390
2391 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002392 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002393 dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002394 break;
Michael Wright227c5542020-07-02 18:30:52 +01002395 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002396 dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002397 break;
Michael Wright227c5542020-07-02 18:30:52 +01002398 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002399 dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002400 break;
Michael Wright227c5542020-07-02 18:30:52 +01002401 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002402 break;
2403 }
2404}
2405
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002406void TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002407 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002408 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002409 abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002410 break;
Michael Wright227c5542020-07-02 18:30:52 +01002411 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002412 abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002413 break;
Michael Wright227c5542020-07-02 18:30:52 +01002414 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002415 abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002416 break;
Michael Wright227c5542020-07-02 18:30:52 +01002417 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002418 break;
2419 }
2420
Michael Wright227c5542020-07-02 18:30:52 +01002421 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002422}
2423
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002424void TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
2425 bool isTimeout) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002426 // Update current gesture coordinates.
2427 bool cancelPreviousGesture, finishPreviousGesture;
2428 bool sendEvents =
2429 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2430 if (!sendEvents) {
2431 return;
2432 }
2433 if (finishPreviousGesture) {
2434 cancelPreviousGesture = false;
2435 }
2436
2437 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002438 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002439 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002440 if (finishPreviousGesture || cancelPreviousGesture) {
2441 mPointerController->clearSpots();
2442 }
2443
Michael Wright227c5542020-07-02 18:30:52 +01002444 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002445 setTouchSpots(mPointerGesture.currentGestureCoords,
2446 mPointerGesture.currentGestureIdToIndex,
2447 mPointerGesture.currentGestureIdBits, mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002448 }
2449 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002450 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002451 }
2452
2453 // Show or hide the pointer if needed.
2454 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002455 case PointerGesture::Mode::NEUTRAL:
2456 case PointerGesture::Mode::QUIET:
2457 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2458 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002459 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002460 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002461 }
2462 break;
Michael Wright227c5542020-07-02 18:30:52 +01002463 case PointerGesture::Mode::TAP:
2464 case PointerGesture::Mode::TAP_DRAG:
2465 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2466 case PointerGesture::Mode::HOVER:
2467 case PointerGesture::Mode::PRESS:
2468 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002469 // Unfade the pointer when the current gesture manipulates the
2470 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002471 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002472 break;
Michael Wright227c5542020-07-02 18:30:52 +01002473 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002474 // Fade the pointer when the current gesture manipulates a different
2475 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002476 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002477 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002478 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002479 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002480 }
2481 break;
2482 }
2483
2484 // Send events!
2485 int32_t metaState = getContext()->getGlobalMetaState();
2486 int32_t buttonState = mCurrentCookedState.buttonState;
2487
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002488 uint32_t flags = 0;
2489
2490 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2491 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2492 }
2493
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002494 // Update last coordinates of pointers that have moved so that we observe the new
2495 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002496 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2497 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2498 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2499 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2500 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2501 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002502 bool moveNeeded = false;
2503 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2504 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2505 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2506 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2507 mPointerGesture.lastGestureIdBits.value);
2508 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2509 mPointerGesture.currentGestureCoords,
2510 mPointerGesture.currentGestureIdToIndex,
2511 mPointerGesture.lastGestureProperties,
2512 mPointerGesture.lastGestureCoords,
2513 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2514 if (buttonState != mLastCookedState.buttonState) {
2515 moveNeeded = true;
2516 }
2517 }
2518
2519 // Send motion events for all pointers that went up or were canceled.
2520 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2521 if (!dispatchedGestureIdBits.isEmpty()) {
2522 if (cancelPreviousGesture) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002523 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0,
2524 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002525 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2526 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2527 mPointerGesture.downTime);
2528
2529 dispatchedGestureIdBits.clear();
2530 } else {
2531 BitSet32 upGestureIdBits;
2532 if (finishPreviousGesture) {
2533 upGestureIdBits = dispatchedGestureIdBits;
2534 } else {
2535 upGestureIdBits.value =
2536 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2537 }
2538 while (!upGestureIdBits.isEmpty()) {
2539 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2540
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002541 dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002542 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState, buttonState,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002543 AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002544 mPointerGesture.lastGestureCoords,
2545 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2546 0, mPointerGesture.downTime);
2547
2548 dispatchedGestureIdBits.clearBit(id);
2549 }
2550 }
2551 }
2552
2553 // Send motion events for all pointers that moved.
2554 if (moveNeeded) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002555 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002556 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002557 mPointerGesture.currentGestureProperties,
2558 mPointerGesture.currentGestureCoords,
2559 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2560 mPointerGesture.downTime);
2561 }
2562
2563 // Send motion events for all pointers that went down.
2564 if (down) {
2565 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2566 ~dispatchedGestureIdBits.value);
2567 while (!downGestureIdBits.isEmpty()) {
2568 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2569 dispatchedGestureIdBits.markBit(id);
2570
2571 if (dispatchedGestureIdBits.count() == 1) {
2572 mPointerGesture.downTime = when;
2573 }
2574
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002575 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002576 0, flags, metaState, buttonState, 0,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002577 mPointerGesture.currentGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002578 mPointerGesture.currentGestureCoords,
2579 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2580 0, mPointerGesture.downTime);
2581 }
2582 }
2583
2584 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002585 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002586 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2587 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002588 mPointerGesture.currentGestureProperties,
2589 mPointerGesture.currentGestureCoords,
2590 mPointerGesture.currentGestureIdToIndex,
2591 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2592 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2593 // Synthesize a hover move event after all pointers go up to indicate that
2594 // the pointer is hovering again even if the user is not currently touching
2595 // the touch pad. This ensures that a view will receive a fresh hover enter
2596 // event after a tap.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002597 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002598
2599 PointerProperties pointerProperties;
2600 pointerProperties.clear();
2601 pointerProperties.id = 0;
2602 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2603
2604 PointerCoords pointerCoords;
2605 pointerCoords.clear();
2606 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2607 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2608
2609 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002610 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002611 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002612 metaState, buttonState, MotionClassification::NONE,
2613 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
2614 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00002615 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002616 }
2617
2618 // Update state.
2619 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2620 if (!down) {
2621 mPointerGesture.lastGestureIdBits.clear();
2622 } else {
2623 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2624 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2625 uint32_t id = idBits.clearFirstMarkedBit();
2626 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2627 mPointerGesture.lastGestureProperties[index].copyFrom(
2628 mPointerGesture.currentGestureProperties[index]);
2629 mPointerGesture.lastGestureCoords[index].copyFrom(
2630 mPointerGesture.currentGestureCoords[index]);
2631 mPointerGesture.lastGestureIdToIndex[id] = index;
2632 }
2633 }
2634}
2635
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002636void TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002637 // Cancel previously dispatches pointers.
2638 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2639 int32_t metaState = getContext()->getGlobalMetaState();
2640 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002641 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
2642 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002643 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2644 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2645 0, 0, mPointerGesture.downTime);
2646 }
2647
2648 // Reset the current pointer gesture.
2649 mPointerGesture.reset();
2650 mPointerVelocityControl.reset();
2651
2652 // Remove any current spots.
2653 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002654 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002655 mPointerController->clearSpots();
2656 }
2657}
2658
2659bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2660 bool* outFinishPreviousGesture, bool isTimeout) {
2661 *outCancelPreviousGesture = false;
2662 *outFinishPreviousGesture = false;
2663
2664 // Handle TAP timeout.
2665 if (isTimeout) {
2666#if DEBUG_GESTURES
2667 ALOGD("Gestures: Processing timeout");
2668#endif
2669
Michael Wright227c5542020-07-02 18:30:52 +01002670 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002671 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2672 // The tap/drag timeout has not yet expired.
2673 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2674 mConfig.pointerGestureTapDragInterval);
2675 } else {
2676 // The tap is finished.
2677#if DEBUG_GESTURES
2678 ALOGD("Gestures: TAP finished");
2679#endif
2680 *outFinishPreviousGesture = true;
2681
2682 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002683 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002684 mPointerGesture.currentGestureIdBits.clear();
2685
2686 mPointerVelocityControl.reset();
2687 return true;
2688 }
2689 }
2690
2691 // We did not handle this timeout.
2692 return false;
2693 }
2694
2695 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2696 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2697
2698 // Update the velocity tracker.
2699 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002700 std::vector<VelocityTracker::Position> positions;
2701 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002702 uint32_t id = idBits.clearFirstMarkedBit();
2703 const RawPointerData::Pointer& pointer =
2704 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002705 float x = pointer.x * mPointerXMovementScale;
2706 float y = pointer.y * mPointerYMovementScale;
2707 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002708 }
2709 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2710 positions);
2711 }
2712
2713 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2714 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002715 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2716 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2717 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002718 mPointerGesture.resetTap();
2719 }
2720
2721 // Pick a new active touch id if needed.
2722 // Choose an arbitrary pointer that just went down, if there is one.
2723 // Otherwise choose an arbitrary remaining pointer.
2724 // This guarantees we always have an active touch id when there is at least one pointer.
2725 // We keep the same active touch id for as long as possible.
2726 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2727 int32_t activeTouchId = lastActiveTouchId;
2728 if (activeTouchId < 0) {
2729 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2730 activeTouchId = mPointerGesture.activeTouchId =
2731 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2732 mPointerGesture.firstTouchTime = when;
2733 }
2734 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2735 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2736 activeTouchId = mPointerGesture.activeTouchId =
2737 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2738 } else {
2739 activeTouchId = mPointerGesture.activeTouchId = -1;
2740 }
2741 }
2742
2743 // Determine whether we are in quiet time.
2744 bool isQuietTime = false;
2745 if (activeTouchId < 0) {
2746 mPointerGesture.resetQuietTime();
2747 } else {
2748 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2749 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002750 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2751 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2752 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002753 currentFingerCount < 2) {
2754 // Enter quiet time when exiting swipe or freeform state.
2755 // This is to prevent accidentally entering the hover state and flinging the
2756 // pointer when finishing a swipe and there is still one pointer left onscreen.
2757 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002758 } else if (mPointerGesture.lastGestureMode ==
2759 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002760 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2761 // Enter quiet time when releasing the button and there are still two or more
2762 // fingers down. This may indicate that one finger was used to press the button
2763 // but it has not gone up yet.
2764 isQuietTime = true;
2765 }
2766 if (isQuietTime) {
2767 mPointerGesture.quietTime = when;
2768 }
2769 }
2770 }
2771
2772 // Switch states based on button and pointer state.
2773 if (isQuietTime) {
2774 // Case 1: Quiet time. (QUIET)
2775#if DEBUG_GESTURES
2776 ALOGD("Gestures: QUIET for next %0.3fms",
2777 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2778#endif
Michael Wright227c5542020-07-02 18:30:52 +01002779 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002780 *outFinishPreviousGesture = true;
2781 }
2782
2783 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002784 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002785 mPointerGesture.currentGestureIdBits.clear();
2786
2787 mPointerVelocityControl.reset();
2788 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2789 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2790 // The pointer follows the active touch point.
2791 // Emit DOWN, MOVE, UP events at the pointer location.
2792 //
2793 // Only the active touch matters; other fingers are ignored. This policy helps
2794 // to handle the case where the user places a second finger on the touch pad
2795 // to apply the necessary force to depress an integrated button below the surface.
2796 // We don't want the second finger to be delivered to applications.
2797 //
2798 // For this to work well, we need to make sure to track the pointer that is really
2799 // active. If the user first puts one finger down to click then adds another
2800 // finger to drag then the active pointer should switch to the finger that is
2801 // being dragged.
2802#if DEBUG_GESTURES
2803 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2804 "currentFingerCount=%d",
2805 activeTouchId, currentFingerCount);
2806#endif
2807 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002808 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002809 *outFinishPreviousGesture = true;
2810 mPointerGesture.activeGestureId = 0;
2811 }
2812
2813 // Switch pointers if needed.
2814 // Find the fastest pointer and follow it.
2815 if (activeTouchId >= 0 && currentFingerCount > 1) {
2816 int32_t bestId = -1;
2817 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2818 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2819 uint32_t id = idBits.clearFirstMarkedBit();
2820 float vx, vy;
2821 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2822 float speed = hypotf(vx, vy);
2823 if (speed > bestSpeed) {
2824 bestId = id;
2825 bestSpeed = speed;
2826 }
2827 }
2828 }
2829 if (bestId >= 0 && bestId != activeTouchId) {
2830 mPointerGesture.activeTouchId = activeTouchId = bestId;
2831#if DEBUG_GESTURES
2832 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2833 "bestId=%d, bestSpeed=%0.3f",
2834 bestId, bestSpeed);
2835#endif
2836 }
2837 }
2838
2839 float deltaX = 0, deltaY = 0;
2840 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2841 const RawPointerData::Pointer& currentPointer =
2842 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2843 const RawPointerData::Pointer& lastPointer =
2844 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2845 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2846 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2847
2848 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2849 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2850
2851 // Move the pointer using a relative motion.
2852 // When using spots, the click will occur at the position of the anchor
2853 // spot and all other spots will move there.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002854 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002855 } else {
2856 mPointerVelocityControl.reset();
2857 }
2858
Prabir Pradhand7482e72021-03-09 13:54:55 -08002859 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002860
Michael Wright227c5542020-07-02 18:30:52 +01002861 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002862 mPointerGesture.currentGestureIdBits.clear();
2863 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2864 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2865 mPointerGesture.currentGestureProperties[0].clear();
2866 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2867 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2868 mPointerGesture.currentGestureCoords[0].clear();
2869 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2870 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2871 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2872 } else if (currentFingerCount == 0) {
2873 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002874 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002875 *outFinishPreviousGesture = true;
2876 }
2877
2878 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2879 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2880 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002881 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2882 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002883 lastFingerCount == 1) {
2884 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002885 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002886 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2887 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2888#if DEBUG_GESTURES
2889 ALOGD("Gestures: TAP");
2890#endif
2891
2892 mPointerGesture.tapUpTime = when;
2893 getContext()->requestTimeoutAtTime(when +
2894 mConfig.pointerGestureTapDragInterval);
2895
2896 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002897 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002898 mPointerGesture.currentGestureIdBits.clear();
2899 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2900 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2901 mPointerGesture.currentGestureProperties[0].clear();
2902 mPointerGesture.currentGestureProperties[0].id =
2903 mPointerGesture.activeGestureId;
2904 mPointerGesture.currentGestureProperties[0].toolType =
2905 AMOTION_EVENT_TOOL_TYPE_FINGER;
2906 mPointerGesture.currentGestureCoords[0].clear();
2907 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2908 mPointerGesture.tapX);
2909 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2910 mPointerGesture.tapY);
2911 mPointerGesture.currentGestureCoords[0]
2912 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2913
2914 tapped = true;
2915 } else {
2916#if DEBUG_GESTURES
2917 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2918 y - mPointerGesture.tapY);
2919#endif
2920 }
2921 } else {
2922#if DEBUG_GESTURES
2923 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2924 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2925 (when - mPointerGesture.tapDownTime) * 0.000001f);
2926 } else {
2927 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2928 }
2929#endif
2930 }
2931 }
2932
2933 mPointerVelocityControl.reset();
2934
2935 if (!tapped) {
2936#if DEBUG_GESTURES
2937 ALOGD("Gestures: NEUTRAL");
2938#endif
2939 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002940 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002941 mPointerGesture.currentGestureIdBits.clear();
2942 }
2943 } else if (currentFingerCount == 1) {
2944 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2945 // The pointer follows the active touch point.
2946 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2947 // When in TAP_DRAG, emit MOVE events at the pointer location.
2948 ALOG_ASSERT(activeTouchId >= 0);
2949
Michael Wright227c5542020-07-02 18:30:52 +01002950 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2951 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002952 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002953 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002954 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2955 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002956 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002957 } else {
2958#if DEBUG_GESTURES
2959 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2960 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2961#endif
2962 }
2963 } else {
2964#if DEBUG_GESTURES
2965 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2966 (when - mPointerGesture.tapUpTime) * 0.000001f);
2967#endif
2968 }
Michael Wright227c5542020-07-02 18:30:52 +01002969 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2970 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002971 }
2972
2973 float deltaX = 0, deltaY = 0;
2974 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2975 const RawPointerData::Pointer& currentPointer =
2976 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2977 const RawPointerData::Pointer& lastPointer =
2978 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2979 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2980 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2981
2982 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2983 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2984
2985 // Move the pointer using a relative motion.
2986 // When using spots, the hover or drag will occur at the position of the anchor spot.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002987 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002988 } else {
2989 mPointerVelocityControl.reset();
2990 }
2991
2992 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01002993 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002994#if DEBUG_GESTURES
2995 ALOGD("Gestures: TAP_DRAG");
2996#endif
2997 down = true;
2998 } else {
2999#if DEBUG_GESTURES
3000 ALOGD("Gestures: HOVER");
3001#endif
Michael Wright227c5542020-07-02 18:30:52 +01003002 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003003 *outFinishPreviousGesture = true;
3004 }
3005 mPointerGesture.activeGestureId = 0;
3006 down = false;
3007 }
3008
Prabir Pradhand7482e72021-03-09 13:54:55 -08003009 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003010
3011 mPointerGesture.currentGestureIdBits.clear();
3012 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3013 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3014 mPointerGesture.currentGestureProperties[0].clear();
3015 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3016 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3017 mPointerGesture.currentGestureCoords[0].clear();
3018 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3019 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3020 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3021 down ? 1.0f : 0.0f);
3022
3023 if (lastFingerCount == 0 && currentFingerCount != 0) {
3024 mPointerGesture.resetTap();
3025 mPointerGesture.tapDownTime = when;
3026 mPointerGesture.tapX = x;
3027 mPointerGesture.tapY = y;
3028 }
3029 } else {
3030 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
3031 // We need to provide feedback for each finger that goes down so we cannot wait
3032 // for the fingers to move before deciding what to do.
3033 //
3034 // The ambiguous case is deciding what to do when there are two fingers down but they
3035 // have not moved enough to determine whether they are part of a drag or part of a
3036 // freeform gesture, or just a press or long-press at the pointer location.
3037 //
3038 // When there are two fingers we start with the PRESS hypothesis and we generate a
3039 // down at the pointer location.
3040 //
3041 // When the two fingers move enough or when additional fingers are added, we make
3042 // a decision to transition into SWIPE or FREEFORM mode accordingly.
3043 ALOG_ASSERT(activeTouchId >= 0);
3044
3045 bool settled = when >=
3046 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01003047 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3048 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3049 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003050 *outFinishPreviousGesture = true;
3051 } else if (!settled && currentFingerCount > lastFingerCount) {
3052 // Additional pointers have gone down but not yet settled.
3053 // Reset the gesture.
3054#if DEBUG_GESTURES
3055 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
3056 "settle time remaining %0.3fms",
3057 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3058 when) * 0.000001f);
3059#endif
3060 *outCancelPreviousGesture = true;
3061 } else {
3062 // Continue previous gesture.
3063 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3064 }
3065
3066 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01003067 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003068 mPointerGesture.activeGestureId = 0;
3069 mPointerGesture.referenceIdBits.clear();
3070 mPointerVelocityControl.reset();
3071
3072 // Use the centroid and pointer location as the reference points for the gesture.
3073#if DEBUG_GESTURES
3074 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3075 "settle time remaining %0.3fms",
3076 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3077 when) * 0.000001f);
3078#endif
3079 mCurrentRawState.rawPointerData
3080 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3081 &mPointerGesture.referenceTouchY);
Prabir Pradhand7482e72021-03-09 13:54:55 -08003082 auto [x, y] = getMouseCursorPosition();
3083 mPointerGesture.referenceGestureX = x;
3084 mPointerGesture.referenceGestureY = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003085 }
3086
3087 // Clear the reference deltas for fingers not yet included in the reference calculation.
3088 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3089 ~mPointerGesture.referenceIdBits.value);
3090 !idBits.isEmpty();) {
3091 uint32_t id = idBits.clearFirstMarkedBit();
3092 mPointerGesture.referenceDeltas[id].dx = 0;
3093 mPointerGesture.referenceDeltas[id].dy = 0;
3094 }
3095 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3096
3097 // Add delta for all fingers and calculate a common movement delta.
3098 float commonDeltaX = 0, commonDeltaY = 0;
3099 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3100 mCurrentCookedState.fingerIdBits.value);
3101 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3102 bool first = (idBits == commonIdBits);
3103 uint32_t id = idBits.clearFirstMarkedBit();
3104 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3105 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3106 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3107 delta.dx += cpd.x - lpd.x;
3108 delta.dy += cpd.y - lpd.y;
3109
3110 if (first) {
3111 commonDeltaX = delta.dx;
3112 commonDeltaY = delta.dy;
3113 } else {
3114 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3115 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3116 }
3117 }
3118
3119 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003120 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003121 float dist[MAX_POINTER_ID + 1];
3122 int32_t distOverThreshold = 0;
3123 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3124 uint32_t id = idBits.clearFirstMarkedBit();
3125 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3126 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3127 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3128 distOverThreshold += 1;
3129 }
3130 }
3131
3132 // Only transition when at least two pointers have moved further than
3133 // the minimum distance threshold.
3134 if (distOverThreshold >= 2) {
3135 if (currentFingerCount > 2) {
3136 // There are more than two pointers, switch to FREEFORM.
3137#if DEBUG_GESTURES
3138 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3139 currentFingerCount);
3140#endif
3141 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003142 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003143 } else {
3144 // There are exactly two pointers.
3145 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3146 uint32_t id1 = idBits.clearFirstMarkedBit();
3147 uint32_t id2 = idBits.firstMarkedBit();
3148 const RawPointerData::Pointer& p1 =
3149 mCurrentRawState.rawPointerData.pointerForId(id1);
3150 const RawPointerData::Pointer& p2 =
3151 mCurrentRawState.rawPointerData.pointerForId(id2);
3152 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3153 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3154 // There are two pointers but they are too far apart for a SWIPE,
3155 // switch to FREEFORM.
3156#if DEBUG_GESTURES
3157 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3158 mutualDistance, mPointerGestureMaxSwipeWidth);
3159#endif
3160 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003161 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003162 } else {
3163 // There are two pointers. Wait for both pointers to start moving
3164 // before deciding whether this is a SWIPE or FREEFORM gesture.
3165 float dist1 = dist[id1];
3166 float dist2 = dist[id2];
3167 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3168 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3169 // Calculate the dot product of the displacement vectors.
3170 // When the vectors are oriented in approximately the same direction,
3171 // the angle betweeen them is near zero and the cosine of the angle
3172 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3173 // mag(v2).
3174 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3175 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3176 float dx1 = delta1.dx * mPointerXZoomScale;
3177 float dy1 = delta1.dy * mPointerYZoomScale;
3178 float dx2 = delta2.dx * mPointerXZoomScale;
3179 float dy2 = delta2.dy * mPointerYZoomScale;
3180 float dot = dx1 * dx2 + dy1 * dy2;
3181 float cosine = dot / (dist1 * dist2); // denominator always > 0
3182 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3183 // Pointers are moving in the same direction. Switch to SWIPE.
3184#if DEBUG_GESTURES
3185 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3186 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3187 "cosine %0.3f >= %0.3f",
3188 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3189 mConfig.pointerGestureMultitouchMinDistance, cosine,
3190 mConfig.pointerGestureSwipeTransitionAngleCosine);
3191#endif
Michael Wright227c5542020-07-02 18:30:52 +01003192 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003193 } else {
3194 // Pointers are moving in different directions. Switch to FREEFORM.
3195#if DEBUG_GESTURES
3196 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3197 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3198 "cosine %0.3f < %0.3f",
3199 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3200 mConfig.pointerGestureMultitouchMinDistance, cosine,
3201 mConfig.pointerGestureSwipeTransitionAngleCosine);
3202#endif
3203 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003204 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003205 }
3206 }
3207 }
3208 }
3209 }
Michael Wright227c5542020-07-02 18:30:52 +01003210 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003211 // Switch from SWIPE to FREEFORM if additional pointers go down.
3212 // Cancel previous gesture.
3213 if (currentFingerCount > 2) {
3214#if DEBUG_GESTURES
3215 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3216 currentFingerCount);
3217#endif
3218 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003219 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003220 }
3221 }
3222
3223 // Move the reference points based on the overall group motion of the fingers
3224 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003225 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003226 (commonDeltaX || commonDeltaY)) {
3227 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3228 uint32_t id = idBits.clearFirstMarkedBit();
3229 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3230 delta.dx = 0;
3231 delta.dy = 0;
3232 }
3233
3234 mPointerGesture.referenceTouchX += commonDeltaX;
3235 mPointerGesture.referenceTouchY += commonDeltaY;
3236
3237 commonDeltaX *= mPointerXMovementScale;
3238 commonDeltaY *= mPointerYMovementScale;
3239
3240 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3241 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3242
3243 mPointerGesture.referenceGestureX += commonDeltaX;
3244 mPointerGesture.referenceGestureY += commonDeltaY;
3245 }
3246
3247 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003248 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3249 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003250 // PRESS or SWIPE mode.
3251#if DEBUG_GESTURES
3252 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3253 "activeGestureId=%d, currentTouchPointerCount=%d",
3254 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3255#endif
3256 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3257
3258 mPointerGesture.currentGestureIdBits.clear();
3259 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3260 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3261 mPointerGesture.currentGestureProperties[0].clear();
3262 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3263 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3264 mPointerGesture.currentGestureCoords[0].clear();
3265 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3266 mPointerGesture.referenceGestureX);
3267 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3268 mPointerGesture.referenceGestureY);
3269 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003270 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003271 // FREEFORM mode.
3272#if DEBUG_GESTURES
3273 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3274 "activeGestureId=%d, currentTouchPointerCount=%d",
3275 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3276#endif
3277 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3278
3279 mPointerGesture.currentGestureIdBits.clear();
3280
3281 BitSet32 mappedTouchIdBits;
3282 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003283 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003284 // Initially, assign the active gesture id to the active touch point
3285 // if there is one. No other touch id bits are mapped yet.
3286 if (!*outCancelPreviousGesture) {
3287 mappedTouchIdBits.markBit(activeTouchId);
3288 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3289 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3290 mPointerGesture.activeGestureId;
3291 } else {
3292 mPointerGesture.activeGestureId = -1;
3293 }
3294 } else {
3295 // Otherwise, assume we mapped all touches from the previous frame.
3296 // Reuse all mappings that are still applicable.
3297 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3298 mCurrentCookedState.fingerIdBits.value;
3299 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3300
3301 // Check whether we need to choose a new active gesture id because the
3302 // current went went up.
3303 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3304 ~mCurrentCookedState.fingerIdBits.value);
3305 !upTouchIdBits.isEmpty();) {
3306 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3307 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3308 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3309 mPointerGesture.activeGestureId = -1;
3310 break;
3311 }
3312 }
3313 }
3314
3315#if DEBUG_GESTURES
3316 ALOGD("Gestures: FREEFORM follow up "
3317 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3318 "activeGestureId=%d",
3319 mappedTouchIdBits.value, usedGestureIdBits.value,
3320 mPointerGesture.activeGestureId);
3321#endif
3322
3323 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3324 for (uint32_t i = 0; i < currentFingerCount; i++) {
3325 uint32_t touchId = idBits.clearFirstMarkedBit();
3326 uint32_t gestureId;
3327 if (!mappedTouchIdBits.hasBit(touchId)) {
3328 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3329 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3330#if DEBUG_GESTURES
3331 ALOGD("Gestures: FREEFORM "
3332 "new mapping for touch id %d -> gesture id %d",
3333 touchId, gestureId);
3334#endif
3335 } else {
3336 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3337#if DEBUG_GESTURES
3338 ALOGD("Gestures: FREEFORM "
3339 "existing mapping for touch id %d -> gesture id %d",
3340 touchId, gestureId);
3341#endif
3342 }
3343 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3344 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3345
3346 const RawPointerData::Pointer& pointer =
3347 mCurrentRawState.rawPointerData.pointerForId(touchId);
3348 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3349 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3350 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3351
3352 mPointerGesture.currentGestureProperties[i].clear();
3353 mPointerGesture.currentGestureProperties[i].id = gestureId;
3354 mPointerGesture.currentGestureProperties[i].toolType =
3355 AMOTION_EVENT_TOOL_TYPE_FINGER;
3356 mPointerGesture.currentGestureCoords[i].clear();
3357 mPointerGesture.currentGestureCoords[i]
3358 .setAxisValue(AMOTION_EVENT_AXIS_X,
3359 mPointerGesture.referenceGestureX + deltaX);
3360 mPointerGesture.currentGestureCoords[i]
3361 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3362 mPointerGesture.referenceGestureY + deltaY);
3363 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3364 1.0f);
3365 }
3366
3367 if (mPointerGesture.activeGestureId < 0) {
3368 mPointerGesture.activeGestureId =
3369 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3370#if DEBUG_GESTURES
3371 ALOGD("Gestures: FREEFORM new "
3372 "activeGestureId=%d",
3373 mPointerGesture.activeGestureId);
3374#endif
3375 }
3376 }
3377 }
3378
3379 mPointerController->setButtonState(mCurrentRawState.buttonState);
3380
3381#if DEBUG_GESTURES
3382 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3383 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3384 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3385 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3386 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3387 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3388 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3389 uint32_t id = idBits.clearFirstMarkedBit();
3390 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3391 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3392 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3393 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3394 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3395 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3396 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3397 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3398 }
3399 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3400 uint32_t id = idBits.clearFirstMarkedBit();
3401 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3402 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3403 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3404 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3405 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3406 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3407 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3408 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3409 }
3410#endif
3411 return true;
3412}
3413
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003414void TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003415 mPointerSimple.currentCoords.clear();
3416 mPointerSimple.currentProperties.clear();
3417
3418 bool down, hovering;
3419 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3420 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3421 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhand7482e72021-03-09 13:54:55 -08003422 setMouseCursorPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3423 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003424
3425 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3426 down = !hovering;
3427
Prabir Pradhand7482e72021-03-09 13:54:55 -08003428 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003429 mPointerSimple.currentCoords.copyFrom(
3430 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3431 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3432 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3433 mPointerSimple.currentProperties.id = 0;
3434 mPointerSimple.currentProperties.toolType =
3435 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3436 } else {
3437 down = false;
3438 hovering = false;
3439 }
3440
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003441 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003442}
3443
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003444void TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3445 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003446}
3447
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003448void TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003449 mPointerSimple.currentCoords.clear();
3450 mPointerSimple.currentProperties.clear();
3451
3452 bool down, hovering;
3453 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3454 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3455 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3456 float deltaX = 0, deltaY = 0;
3457 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3458 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3459 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3460 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3461 mPointerXMovementScale;
3462 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3463 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3464 mPointerYMovementScale;
3465
3466 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3467 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3468
Prabir Pradhand7482e72021-03-09 13:54:55 -08003469 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003470 } else {
3471 mPointerVelocityControl.reset();
3472 }
3473
3474 down = isPointerDown(mCurrentRawState.buttonState);
3475 hovering = !down;
3476
Prabir Pradhand7482e72021-03-09 13:54:55 -08003477 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003478 mPointerSimple.currentCoords.copyFrom(
3479 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3480 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3481 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3482 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3483 hovering ? 0.0f : 1.0f);
3484 mPointerSimple.currentProperties.id = 0;
3485 mPointerSimple.currentProperties.toolType =
3486 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3487 } else {
3488 mPointerVelocityControl.reset();
3489
3490 down = false;
3491 hovering = false;
3492 }
3493
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003494 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003495}
3496
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003497void TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3498 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003499
3500 mPointerVelocityControl.reset();
3501}
3502
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003503void TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3504 bool down, bool hovering) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003505 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003506
3507 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003508 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003509 mPointerController->clearSpots();
3510 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003511 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003512 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003513 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003514 }
Garfield Tan9514d782020-11-10 16:37:23 -08003515 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003516
Prabir Pradhand7482e72021-03-09 13:54:55 -08003517 auto [xCursorPosition, yCursorPosition] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003518
3519 if (mPointerSimple.down && !down) {
3520 mPointerSimple.down = false;
3521
3522 // Send up.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003523 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3524 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003525 mLastRawState.buttonState, MotionClassification::NONE,
3526 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3527 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3528 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3529 /* videoFrames */ {});
3530 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003531 }
3532
3533 if (mPointerSimple.hovering && !hovering) {
3534 mPointerSimple.hovering = false;
3535
3536 // Send hover exit.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003537 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3538 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3539 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003540 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3541 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3542 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3543 /* videoFrames */ {});
3544 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003545 }
3546
3547 if (down) {
3548 if (!mPointerSimple.down) {
3549 mPointerSimple.down = true;
3550 mPointerSimple.downTime = when;
3551
3552 // Send down.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003553 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003554 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3555 metaState, mCurrentRawState.buttonState,
3556 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3557 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3558 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3559 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3560 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003561 }
3562
3563 // Send move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003564 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3565 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003566 mCurrentRawState.buttonState, MotionClassification::NONE,
3567 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3568 &mPointerSimple.currentCoords, mOrientedXPrecision,
3569 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3570 mPointerSimple.downTime, /* videoFrames */ {});
3571 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003572 }
3573
3574 if (hovering) {
3575 if (!mPointerSimple.hovering) {
3576 mPointerSimple.hovering = true;
3577
3578 // Send hover enter.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003579 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003580 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3581 metaState, mCurrentRawState.buttonState,
3582 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3583 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3584 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3585 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3586 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003587 }
3588
3589 // Send hover move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003590 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3591 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3592 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003593 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3594 &mPointerSimple.currentCoords, mOrientedXPrecision,
3595 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3596 mPointerSimple.downTime, /* videoFrames */ {});
3597 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003598 }
3599
3600 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3601 float vscroll = mCurrentRawState.rawVScroll;
3602 float hscroll = mCurrentRawState.rawHScroll;
3603 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3604 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3605
3606 // Send scroll.
3607 PointerCoords pointerCoords;
3608 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3609 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3610 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3611
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003612 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3613 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003614 mCurrentRawState.buttonState, MotionClassification::NONE,
3615 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3616 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3617 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3618 /* videoFrames */ {});
3619 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003620 }
3621
3622 // Save state.
3623 if (down || hovering) {
3624 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3625 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3626 } else {
3627 mPointerSimple.reset();
3628 }
3629}
3630
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003631void TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003632 mPointerSimple.currentCoords.clear();
3633 mPointerSimple.currentProperties.clear();
3634
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003635 dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003636}
3637
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003638void TouchInputMapper::dispatchMotion(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3639 uint32_t source, int32_t action, int32_t actionButton,
3640 int32_t flags, int32_t metaState, int32_t buttonState,
3641 int32_t edgeFlags, const PointerProperties* properties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003642 const PointerCoords* coords, const uint32_t* idToIndex,
3643 BitSet32 idBits, int32_t changedId, float xPrecision,
3644 float yPrecision, nsecs_t downTime) {
3645 PointerCoords pointerCoords[MAX_POINTERS];
3646 PointerProperties pointerProperties[MAX_POINTERS];
3647 uint32_t pointerCount = 0;
3648 while (!idBits.isEmpty()) {
3649 uint32_t id = idBits.clearFirstMarkedBit();
3650 uint32_t index = idToIndex[id];
3651 pointerProperties[pointerCount].copyFrom(properties[index]);
3652 pointerCoords[pointerCount].copyFrom(coords[index]);
3653
3654 if (changedId >= 0 && id == uint32_t(changedId)) {
3655 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3656 }
3657
3658 pointerCount += 1;
3659 }
3660
3661 ALOG_ASSERT(pointerCount != 0);
3662
3663 if (changedId >= 0 && pointerCount == 1) {
3664 // Replace initial down and final up action.
3665 // We can compare the action without masking off the changed pointer index
3666 // because we know the index is 0.
3667 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3668 action = AMOTION_EVENT_ACTION_DOWN;
3669 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003670 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3671 action = AMOTION_EVENT_ACTION_CANCEL;
3672 } else {
3673 action = AMOTION_EVENT_ACTION_UP;
3674 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003675 } else {
3676 // Can't happen.
3677 ALOG_ASSERT(false);
3678 }
3679 }
3680 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3681 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003682 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08003683 auto [x, y] = getMouseCursorPosition();
3684 xCursorPosition = x;
3685 yCursorPosition = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003686 }
3687 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3688 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003689 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003690 std::for_each(frames.begin(), frames.end(),
3691 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003692 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3693 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003694 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3695 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3696 downTime, std::move(frames));
3697 getListener()->notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003698}
3699
3700bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3701 const PointerCoords* inCoords,
3702 const uint32_t* inIdToIndex,
3703 PointerProperties* outProperties,
3704 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3705 BitSet32 idBits) const {
3706 bool changed = false;
3707 while (!idBits.isEmpty()) {
3708 uint32_t id = idBits.clearFirstMarkedBit();
3709 uint32_t inIndex = inIdToIndex[id];
3710 uint32_t outIndex = outIdToIndex[id];
3711
3712 const PointerProperties& curInProperties = inProperties[inIndex];
3713 const PointerCoords& curInCoords = inCoords[inIndex];
3714 PointerProperties& curOutProperties = outProperties[outIndex];
3715 PointerCoords& curOutCoords = outCoords[outIndex];
3716
3717 if (curInProperties != curOutProperties) {
3718 curOutProperties.copyFrom(curInProperties);
3719 changed = true;
3720 }
3721
3722 if (curInCoords != curOutCoords) {
3723 curOutCoords.copyFrom(curInCoords);
3724 changed = true;
3725 }
3726 }
3727 return changed;
3728}
3729
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003730void TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3731 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3732 abortTouches(when, readTime, 0 /* policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003733}
3734
Arthur Hung4197f6b2020-03-16 15:39:59 +08003735// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003736void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003737 // Scale to surface coordinate.
3738 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3739 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3740
arthurhunga36b28e2020-12-29 20:28:15 +08003741 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3742 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3743
Arthur Hung4197f6b2020-03-16 15:39:59 +08003744 // Rotate to surface coordinate.
3745 // 0 - no swap and reverse.
3746 // 90 - swap x/y and reverse y.
3747 // 180 - reverse x, y.
3748 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003749 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003750 case DISPLAY_ORIENTATION_0:
3751 x = xScaled + mXTranslate;
3752 y = yScaled + mYTranslate;
3753 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003754 case DISPLAY_ORIENTATION_90:
arthurhunga36b28e2020-12-29 20:28:15 +08003755 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003756 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003757 break;
3758 case DISPLAY_ORIENTATION_180:
arthurhunga36b28e2020-12-29 20:28:15 +08003759 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3760 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003761 break;
3762 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003763 y = xScaled + mXTranslate;
arthurhunga36b28e2020-12-29 20:28:15 +08003764 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003765 break;
3766 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003767 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003768 }
3769}
3770
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003771bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003772 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3773 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3774
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003775 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003776 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003777 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003778 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003779}
3780
3781const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3782 for (const VirtualKey& virtualKey : mVirtualKeys) {
3783#if DEBUG_VIRTUAL_KEYS
3784 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3785 "left=%d, top=%d, right=%d, bottom=%d",
3786 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3787 virtualKey.hitRight, virtualKey.hitBottom);
3788#endif
3789
3790 if (virtualKey.isHit(x, y)) {
3791 return &virtualKey;
3792 }
3793 }
3794
3795 return nullptr;
3796}
3797
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003798void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3799 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3800 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003801
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003802 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003803
3804 if (currentPointerCount == 0) {
3805 // No pointers to assign.
3806 return;
3807 }
3808
3809 if (lastPointerCount == 0) {
3810 // All pointers are new.
3811 for (uint32_t i = 0; i < currentPointerCount; i++) {
3812 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003813 current.rawPointerData.pointers[i].id = id;
3814 current.rawPointerData.idToIndex[id] = i;
3815 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003816 }
3817 return;
3818 }
3819
3820 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003821 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003822 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003823 uint32_t id = last.rawPointerData.pointers[0].id;
3824 current.rawPointerData.pointers[0].id = id;
3825 current.rawPointerData.idToIndex[id] = 0;
3826 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003827 return;
3828 }
3829
3830 // General case.
3831 // We build a heap of squared euclidean distances between current and last pointers
3832 // associated with the current and last pointer indices. Then, we find the best
3833 // match (by distance) for each current pointer.
3834 // The pointers must have the same tool type but it is possible for them to
3835 // transition from hovering to touching or vice-versa while retaining the same id.
3836 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3837
3838 uint32_t heapSize = 0;
3839 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3840 currentPointerIndex++) {
3841 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3842 lastPointerIndex++) {
3843 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003844 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003845 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003846 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003847 if (currentPointer.toolType == lastPointer.toolType) {
3848 int64_t deltaX = currentPointer.x - lastPointer.x;
3849 int64_t deltaY = currentPointer.y - lastPointer.y;
3850
3851 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3852
3853 // Insert new element into the heap (sift up).
3854 heap[heapSize].currentPointerIndex = currentPointerIndex;
3855 heap[heapSize].lastPointerIndex = lastPointerIndex;
3856 heap[heapSize].distance = distance;
3857 heapSize += 1;
3858 }
3859 }
3860 }
3861
3862 // Heapify
3863 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3864 startIndex -= 1;
3865 for (uint32_t parentIndex = startIndex;;) {
3866 uint32_t childIndex = parentIndex * 2 + 1;
3867 if (childIndex >= heapSize) {
3868 break;
3869 }
3870
3871 if (childIndex + 1 < heapSize &&
3872 heap[childIndex + 1].distance < heap[childIndex].distance) {
3873 childIndex += 1;
3874 }
3875
3876 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3877 break;
3878 }
3879
3880 swap(heap[parentIndex], heap[childIndex]);
3881 parentIndex = childIndex;
3882 }
3883 }
3884
3885#if DEBUG_POINTER_ASSIGNMENT
3886 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3887 for (size_t i = 0; i < heapSize; i++) {
3888 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3889 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3890 }
3891#endif
3892
3893 // Pull matches out by increasing order of distance.
3894 // To avoid reassigning pointers that have already been matched, the loop keeps track
3895 // of which last and current pointers have been matched using the matchedXXXBits variables.
3896 // It also tracks the used pointer id bits.
3897 BitSet32 matchedLastBits(0);
3898 BitSet32 matchedCurrentBits(0);
3899 BitSet32 usedIdBits(0);
3900 bool first = true;
3901 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3902 while (heapSize > 0) {
3903 if (first) {
3904 // The first time through the loop, we just consume the root element of
3905 // the heap (the one with smallest distance).
3906 first = false;
3907 } else {
3908 // Previous iterations consumed the root element of the heap.
3909 // Pop root element off of the heap (sift down).
3910 heap[0] = heap[heapSize];
3911 for (uint32_t parentIndex = 0;;) {
3912 uint32_t childIndex = parentIndex * 2 + 1;
3913 if (childIndex >= heapSize) {
3914 break;
3915 }
3916
3917 if (childIndex + 1 < heapSize &&
3918 heap[childIndex + 1].distance < heap[childIndex].distance) {
3919 childIndex += 1;
3920 }
3921
3922 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3923 break;
3924 }
3925
3926 swap(heap[parentIndex], heap[childIndex]);
3927 parentIndex = childIndex;
3928 }
3929
3930#if DEBUG_POINTER_ASSIGNMENT
3931 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003932 for (size_t j = 0; j < heapSize; j++) {
3933 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3934 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003935 }
3936#endif
3937 }
3938
3939 heapSize -= 1;
3940
3941 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3942 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3943
3944 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3945 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3946
3947 matchedCurrentBits.markBit(currentPointerIndex);
3948 matchedLastBits.markBit(lastPointerIndex);
3949
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003950 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3951 current.rawPointerData.pointers[currentPointerIndex].id = id;
3952 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3953 current.rawPointerData.markIdBit(id,
3954 current.rawPointerData.isHovering(
3955 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003956 usedIdBits.markBit(id);
3957
3958#if DEBUG_POINTER_ASSIGNMENT
3959 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3960 ", distance=%" PRIu64,
3961 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3962#endif
3963 break;
3964 }
3965 }
3966
3967 // Assign fresh ids to pointers that were not matched in the process.
3968 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3969 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3970 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3971
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003972 current.rawPointerData.pointers[currentPointerIndex].id = id;
3973 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3974 current.rawPointerData.markIdBit(id,
3975 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003976
3977#if DEBUG_POINTER_ASSIGNMENT
3978 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3979#endif
3980 }
3981}
3982
3983int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3984 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3985 return AKEY_STATE_VIRTUAL;
3986 }
3987
3988 for (const VirtualKey& virtualKey : mVirtualKeys) {
3989 if (virtualKey.keyCode == keyCode) {
3990 return AKEY_STATE_UP;
3991 }
3992 }
3993
3994 return AKEY_STATE_UNKNOWN;
3995}
3996
3997int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3998 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3999 return AKEY_STATE_VIRTUAL;
4000 }
4001
4002 for (const VirtualKey& virtualKey : mVirtualKeys) {
4003 if (virtualKey.scanCode == scanCode) {
4004 return AKEY_STATE_UP;
4005 }
4006 }
4007
4008 return AKEY_STATE_UNKNOWN;
4009}
4010
4011bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
4012 const int32_t* keyCodes, uint8_t* outFlags) {
4013 for (const VirtualKey& virtualKey : mVirtualKeys) {
4014 for (size_t i = 0; i < numCodes; i++) {
4015 if (virtualKey.keyCode == keyCodes[i]) {
4016 outFlags[i] = 1;
4017 }
4018 }
4019 }
4020
4021 return true;
4022}
4023
4024std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4025 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004026 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004027 return std::make_optional(mPointerController->getDisplayId());
4028 } else {
4029 return std::make_optional(mViewport.displayId);
4030 }
4031 }
4032 return std::nullopt;
4033}
4034
Prabir Pradhand7482e72021-03-09 13:54:55 -08004035void TouchInputMapper::moveMouseCursor(float dx, float dy) const {
4036 if (isPerWindowInputRotationEnabled()) {
4037 // Convert from InputReader's un-rotated coordinate space to PointerController's coordinate
4038 // space that is oriented with the viewport.
4039 rotateDelta(mViewport.orientation, &dx, &dy);
4040 }
4041
4042 mPointerController->move(dx, dy);
4043}
4044
4045std::pair<float, float> TouchInputMapper::getMouseCursorPosition() const {
4046 float x = 0;
4047 float y = 0;
4048 mPointerController->getPosition(&x, &y);
4049
4050 if (!isPerWindowInputRotationEnabled()) return {x, y};
4051 if (!mViewport.isValid()) return {x, y};
4052
4053 // Convert from PointerController's rotated coordinate space that is oriented with the viewport
4054 // to InputReader's un-rotated coordinate space.
4055 const int32_t orientation = getInverseRotation(mViewport.orientation);
4056 rotatePoint(orientation, x, y, mViewport.deviceWidth, mViewport.deviceHeight);
4057 return {x, y};
4058}
4059
4060void TouchInputMapper::setMouseCursorPosition(float x, float y) const {
4061 if (isPerWindowInputRotationEnabled() && mViewport.isValid()) {
4062 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4063 // coordinate space that is oriented with the viewport.
4064 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4065 }
4066
4067 mPointerController->setPosition(x, y);
4068}
4069
4070void TouchInputMapper::setTouchSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex,
4071 BitSet32 spotIdBits, int32_t displayId) {
4072 std::array<PointerCoords, MAX_POINTERS> outSpotCoords{};
4073
4074 for (BitSet32 idBits(spotIdBits); !idBits.isEmpty();) {
4075 const uint32_t index = spotIdToIndex[idBits.clearFirstMarkedBit()];
4076 float x = spotCoords[index].getX();
4077 float y = spotCoords[index].getY();
4078 float pressure = spotCoords[index].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4079
4080 if (isPerWindowInputRotationEnabled()) {
4081 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4082 // coordinate space.
4083 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4084 }
4085
4086 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4087 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4088 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4089 }
4090
4091 mPointerController->setSpots(outSpotCoords.data(), spotIdToIndex, spotIdBits, displayId);
4092}
4093
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004094} // namespace android