blob: fd33df9347c200fe286f15428fc52620d8d7835f [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());
Siarhei Vishniakou18050092021-09-01 13:32:49 -0700402 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 Pradhand7482e72021-03-09 13:54:55 -0800752 if (isPerWindowInputRotationEnabled()) {
Prabir Pradhan5632d622021-09-06 07:57:20 -0700753 // When per-window input rotation is enabled, InputReader works in the display
754 // space, so the surface bounds are the bounds of the display device.
755 const int32_t oldSurfaceWidth = mRawSurfaceWidth;
756 const int32_t oldSurfaceHeight = mRawSurfaceHeight;
757 mRawSurfaceWidth = naturalDeviceWidth;
758 mRawSurfaceHeight = naturalDeviceHeight;
759 mSurfaceLeft = 0;
760 mSurfaceTop = 0;
761 mSurfaceRight = mRawSurfaceWidth;
762 mSurfaceBottom = mRawSurfaceHeight;
Prabir Pradhand7482e72021-03-09 13:54:55 -0800763 // When per-window input rotation is enabled, InputReader works in the un-rotated
764 // coordinate space, so we don't need to do anything if the device is already
765 // orientation-aware. If the device is not orientation-aware, then we need to apply
766 // the inverse rotation of the display so that when the display rotation is applied
767 // later as a part of the per-window transform, we get the expected screen
768 // coordinates.
769 mSurfaceOrientation = mParameters.orientationAware
770 ? DISPLAY_ORIENTATION_0
771 : getInverseRotation(mViewport.orientation);
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700772 // For orientation-aware devices that work in the un-rotated coordinate space, the
773 // viewport update should be skipped if it is only a change in the orientation.
774 skipViewportUpdate = mParameters.orientationAware &&
775 mRawSurfaceWidth == oldSurfaceWidth &&
776 mRawSurfaceHeight == oldSurfaceHeight && viewportOrientationChanged;
Prabir Pradhand7482e72021-03-09 13:54:55 -0800777 } else {
Prabir Pradhan5632d622021-09-06 07:57:20 -0700778 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
779 mRawSurfaceHeight =
780 naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
781 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
782 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
783 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
784 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
785
Prabir Pradhand7482e72021-03-09 13:54:55 -0800786 mSurfaceOrientation = mParameters.orientationAware ? mViewport.orientation
787 : DISPLAY_ORIENTATION_0;
788 }
Prabir Pradhanac1c74f2021-08-20 16:09:32 -0700789
790 // Apply the input device orientation for the device.
791 mSurfaceOrientation =
792 (mSurfaceOrientation + static_cast<int32_t>(mParameters.orientation)) % 4;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700793 } else {
794 mPhysicalWidth = rawWidth;
795 mPhysicalHeight = rawHeight;
796 mPhysicalLeft = 0;
797 mPhysicalTop = 0;
798
Arthur Hung4197f6b2020-03-16 15:39:59 +0800799 mRawSurfaceWidth = rawWidth;
800 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700801 mSurfaceLeft = 0;
802 mSurfaceTop = 0;
803 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
804 }
805 }
806
807 // If moving between pointer modes, need to reset some state.
808 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
809 if (deviceModeChanged) {
810 mOrientedRanges.clear();
811 }
812
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800813 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
814 // preserve the cursor position.
Michael Wright227c5542020-07-02 18:30:52 +0100815 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800816 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000817 (mParameters.deviceType == Parameters::DeviceType::POINTER &&
818 mConfig.pointerCaptureRequest.enable)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800819 if (mPointerController == nullptr) {
820 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700821 }
Prabir Pradhan5cc1a692021-08-06 14:01:18 +0000822 if (mConfig.pointerCaptureRequest.enable) {
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800823 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
824 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700825 } else {
Michael Wright17db18e2020-06-26 20:51:44 +0100826 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700827 }
828
Prabir Pradhan93a0f912021-04-21 13:47:42 -0700829 if ((viewportChanged && !skipViewportUpdate) || deviceModeChanged) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700830 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
831 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800832 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700833 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
834
835 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800836 mXScale = float(mRawSurfaceWidth) / rawWidth;
837 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700838 mXTranslate = -mSurfaceLeft;
839 mYTranslate = -mSurfaceTop;
840 mXPrecision = 1.0f / mXScale;
841 mYPrecision = 1.0f / mYScale;
842
843 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
844 mOrientedRanges.x.source = mSource;
845 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
846 mOrientedRanges.y.source = mSource;
847
848 configureVirtualKeys();
849
850 // Scale factor for terms that are not oriented in a particular axis.
851 // If the pixels are square then xScale == yScale otherwise we fake it
852 // by choosing an average.
853 mGeometricScale = avg(mXScale, mYScale);
854
855 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800856 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700857
858 // Size factors.
Michael Wright227c5542020-07-02 18:30:52 +0100859 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700860 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
861 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
862 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
863 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
864 } else {
865 mSizeScale = 0.0f;
866 }
867
868 mOrientedRanges.haveTouchSize = true;
869 mOrientedRanges.haveToolSize = true;
870 mOrientedRanges.haveSize = true;
871
872 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
873 mOrientedRanges.touchMajor.source = mSource;
874 mOrientedRanges.touchMajor.min = 0;
875 mOrientedRanges.touchMajor.max = diagonalSize;
876 mOrientedRanges.touchMajor.flat = 0;
877 mOrientedRanges.touchMajor.fuzz = 0;
878 mOrientedRanges.touchMajor.resolution = 0;
879
880 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
881 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
882
883 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
884 mOrientedRanges.toolMajor.source = mSource;
885 mOrientedRanges.toolMajor.min = 0;
886 mOrientedRanges.toolMajor.max = diagonalSize;
887 mOrientedRanges.toolMajor.flat = 0;
888 mOrientedRanges.toolMajor.fuzz = 0;
889 mOrientedRanges.toolMajor.resolution = 0;
890
891 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
892 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
893
894 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
895 mOrientedRanges.size.source = mSource;
896 mOrientedRanges.size.min = 0;
897 mOrientedRanges.size.max = 1.0;
898 mOrientedRanges.size.flat = 0;
899 mOrientedRanges.size.fuzz = 0;
900 mOrientedRanges.size.resolution = 0;
901 } else {
902 mSizeScale = 0.0f;
903 }
904
905 // Pressure factors.
906 mPressureScale = 0;
907 float pressureMax = 1.0;
Michael Wright227c5542020-07-02 18:30:52 +0100908 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
909 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700910 if (mCalibration.havePressureScale) {
911 mPressureScale = mCalibration.pressureScale;
912 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
913 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
914 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
915 }
916 }
917
918 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
919 mOrientedRanges.pressure.source = mSource;
920 mOrientedRanges.pressure.min = 0;
921 mOrientedRanges.pressure.max = pressureMax;
922 mOrientedRanges.pressure.flat = 0;
923 mOrientedRanges.pressure.fuzz = 0;
924 mOrientedRanges.pressure.resolution = 0;
925
926 // Tilt
927 mTiltXCenter = 0;
928 mTiltXScale = 0;
929 mTiltYCenter = 0;
930 mTiltYScale = 0;
931 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
932 if (mHaveTilt) {
933 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
934 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
935 mTiltXScale = M_PI / 180;
936 mTiltYScale = M_PI / 180;
937
Tatsunosuke Tobita35e05532021-06-30 14:49:32 +0900938 if (mRawPointerAxes.tiltX.resolution) {
939 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
940 }
941 if (mRawPointerAxes.tiltY.resolution) {
942 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
943 }
944
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700945 mOrientedRanges.haveTilt = true;
946
947 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
948 mOrientedRanges.tilt.source = mSource;
949 mOrientedRanges.tilt.min = 0;
950 mOrientedRanges.tilt.max = M_PI_2;
951 mOrientedRanges.tilt.flat = 0;
952 mOrientedRanges.tilt.fuzz = 0;
953 mOrientedRanges.tilt.resolution = 0;
954 }
955
956 // Orientation
957 mOrientationScale = 0;
958 if (mHaveTilt) {
959 mOrientedRanges.haveOrientation = true;
960
961 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
962 mOrientedRanges.orientation.source = mSource;
963 mOrientedRanges.orientation.min = -M_PI;
964 mOrientedRanges.orientation.max = M_PI;
965 mOrientedRanges.orientation.flat = 0;
966 mOrientedRanges.orientation.fuzz = 0;
967 mOrientedRanges.orientation.resolution = 0;
968 } else if (mCalibration.orientationCalibration !=
Michael Wright227c5542020-07-02 18:30:52 +0100969 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700970 if (mCalibration.orientationCalibration ==
Michael Wright227c5542020-07-02 18:30:52 +0100971 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700972 if (mRawPointerAxes.orientation.valid) {
973 if (mRawPointerAxes.orientation.maxValue > 0) {
974 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
975 } else if (mRawPointerAxes.orientation.minValue < 0) {
976 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
977 } else {
978 mOrientationScale = 0;
979 }
980 }
981 }
982
983 mOrientedRanges.haveOrientation = true;
984
985 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
986 mOrientedRanges.orientation.source = mSource;
987 mOrientedRanges.orientation.min = -M_PI_2;
988 mOrientedRanges.orientation.max = M_PI_2;
989 mOrientedRanges.orientation.flat = 0;
990 mOrientedRanges.orientation.fuzz = 0;
991 mOrientedRanges.orientation.resolution = 0;
992 }
993
994 // Distance
995 mDistanceScale = 0;
Michael Wright227c5542020-07-02 18:30:52 +0100996 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
997 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700998 if (mCalibration.haveDistanceScale) {
999 mDistanceScale = mCalibration.distanceScale;
1000 } else {
1001 mDistanceScale = 1.0f;
1002 }
1003 }
1004
1005 mOrientedRanges.haveDistance = true;
1006
1007 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
1008 mOrientedRanges.distance.source = mSource;
1009 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
1010 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
1011 mOrientedRanges.distance.flat = 0;
1012 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
1013 mOrientedRanges.distance.resolution = 0;
1014 }
1015
1016 // Compute oriented precision, scales and ranges.
1017 // Note that the maximum value reported is an inclusive maximum value so it is one
1018 // unit less than the total width or height of surface.
1019 switch (mSurfaceOrientation) {
1020 case DISPLAY_ORIENTATION_90:
1021 case DISPLAY_ORIENTATION_270:
1022 mOrientedXPrecision = mYPrecision;
1023 mOrientedYPrecision = mXPrecision;
1024
1025 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001026 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001027 mOrientedRanges.x.flat = 0;
1028 mOrientedRanges.x.fuzz = 0;
1029 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
1030
1031 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001032 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001033 mOrientedRanges.y.flat = 0;
1034 mOrientedRanges.y.fuzz = 0;
1035 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
1036 break;
1037
1038 default:
1039 mOrientedXPrecision = mXPrecision;
1040 mOrientedYPrecision = mYPrecision;
1041
1042 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001043 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001044 mOrientedRanges.x.flat = 0;
1045 mOrientedRanges.x.fuzz = 0;
1046 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1047
1048 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001049 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001050 mOrientedRanges.y.flat = 0;
1051 mOrientedRanges.y.fuzz = 0;
1052 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1053 break;
1054 }
1055
1056 // Location
1057 updateAffineTransformation();
1058
Michael Wright227c5542020-07-02 18:30:52 +01001059 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001060 // Compute pointer gesture detection parameters.
1061 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001062 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001063
1064 // Scale movements such that one whole swipe of the touch pad covers a
1065 // given area relative to the diagonal size of the display when no acceleration
1066 // is applied.
1067 // Assume that the touch pad has a square aspect ratio such that movements in
1068 // X and Y of the same number of raw units cover the same physical distance.
1069 mPointerXMovementScale =
1070 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1071 mPointerYMovementScale = mPointerXMovementScale;
1072
1073 // Scale zooms to cover a smaller range of the display than movements do.
1074 // This value determines the area around the pointer that is affected by freeform
1075 // pointer gestures.
1076 mPointerXZoomScale =
1077 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1078 mPointerYZoomScale = mPointerXZoomScale;
1079
1080 // Max width between pointers to detect a swipe gesture is more than some fraction
1081 // of the diagonal axis of the touch pad. Touches that are wider than this are
1082 // translated into freeform gestures.
1083 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1084
1085 // Abort current pointer usages because the state has changed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001086 const nsecs_t readTime = when; // synthetic event
1087 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001088 }
1089
1090 // Inform the dispatcher about the changes.
1091 *outResetNeeded = true;
1092 bumpGeneration();
1093 }
1094}
1095
1096void TouchInputMapper::dumpSurface(std::string& dump) {
1097 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001098 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1099 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001100 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1101 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001102 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1103 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001104 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1105 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1106 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1107 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1108 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1109}
1110
1111void TouchInputMapper::configureVirtualKeys() {
1112 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001113 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001114
1115 mVirtualKeys.clear();
1116
1117 if (virtualKeyDefinitions.size() == 0) {
1118 return;
1119 }
1120
1121 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1122 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1123 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1124 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1125
1126 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1127 VirtualKey virtualKey;
1128
1129 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1130 int32_t keyCode;
1131 int32_t dummyKeyMetaState;
1132 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001133 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1134 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001135 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1136 continue; // drop the key
1137 }
1138
1139 virtualKey.keyCode = keyCode;
1140 virtualKey.flags = flags;
1141
1142 // convert the key definition's display coordinates into touch coordinates for a hit box
1143 int32_t halfWidth = virtualKeyDefinition.width / 2;
1144 int32_t halfHeight = virtualKeyDefinition.height / 2;
1145
1146 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001147 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001148 touchScreenLeft;
1149 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001150 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001151 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001152 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1153 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001154 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001155 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1156 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001157 touchScreenTop;
1158 mVirtualKeys.push_back(virtualKey);
1159 }
1160}
1161
1162void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1163 if (!mVirtualKeys.empty()) {
1164 dump += INDENT3 "Virtual Keys:\n";
1165
1166 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1167 const VirtualKey& virtualKey = mVirtualKeys[i];
1168 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1169 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1170 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1171 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1172 }
1173 }
1174}
1175
1176void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001177 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001178 Calibration& out = mCalibration;
1179
1180 // Size
Michael Wright227c5542020-07-02 18:30:52 +01001181 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001182 String8 sizeCalibrationString;
1183 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1184 if (sizeCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001185 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001186 } else if (sizeCalibrationString == "geometric") {
Michael Wright227c5542020-07-02 18:30:52 +01001187 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001188 } else if (sizeCalibrationString == "diameter") {
Michael Wright227c5542020-07-02 18:30:52 +01001189 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001190 } else if (sizeCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001191 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001192 } else if (sizeCalibrationString == "area") {
Michael Wright227c5542020-07-02 18:30:52 +01001193 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001194 } else if (sizeCalibrationString != "default") {
1195 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1196 }
1197 }
1198
1199 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1200 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1201 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1202
1203 // Pressure
Michael Wright227c5542020-07-02 18:30:52 +01001204 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001205 String8 pressureCalibrationString;
1206 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1207 if (pressureCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001208 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001209 } else if (pressureCalibrationString == "physical") {
Michael Wright227c5542020-07-02 18:30:52 +01001210 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001211 } else if (pressureCalibrationString == "amplitude") {
Michael Wright227c5542020-07-02 18:30:52 +01001212 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001213 } else if (pressureCalibrationString != "default") {
1214 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1215 pressureCalibrationString.string());
1216 }
1217 }
1218
1219 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1220
1221 // Orientation
Michael Wright227c5542020-07-02 18:30:52 +01001222 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001223 String8 orientationCalibrationString;
1224 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1225 if (orientationCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001226 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001227 } else if (orientationCalibrationString == "interpolated") {
Michael Wright227c5542020-07-02 18:30:52 +01001228 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229 } else if (orientationCalibrationString == "vector") {
Michael Wright227c5542020-07-02 18:30:52 +01001230 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001231 } else if (orientationCalibrationString != "default") {
1232 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1233 orientationCalibrationString.string());
1234 }
1235 }
1236
1237 // Distance
Michael Wright227c5542020-07-02 18:30:52 +01001238 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001239 String8 distanceCalibrationString;
1240 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1241 if (distanceCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001242 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001243 } else if (distanceCalibrationString == "scaled") {
Michael Wright227c5542020-07-02 18:30:52 +01001244 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001245 } else if (distanceCalibrationString != "default") {
1246 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1247 distanceCalibrationString.string());
1248 }
1249 }
1250
1251 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1252
Michael Wright227c5542020-07-02 18:30:52 +01001253 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001254 String8 coverageCalibrationString;
1255 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1256 if (coverageCalibrationString == "none") {
Michael Wright227c5542020-07-02 18:30:52 +01001257 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001258 } else if (coverageCalibrationString == "box") {
Michael Wright227c5542020-07-02 18:30:52 +01001259 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001260 } else if (coverageCalibrationString != "default") {
1261 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1262 coverageCalibrationString.string());
1263 }
1264 }
1265}
1266
1267void TouchInputMapper::resolveCalibration() {
1268 // Size
1269 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001270 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1271 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001272 }
1273 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001274 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001275 }
1276
1277 // Pressure
1278 if (mRawPointerAxes.pressure.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001279 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1280 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001281 }
1282 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001283 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001284 }
1285
1286 // Orientation
1287 if (mRawPointerAxes.orientation.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001288 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1289 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001290 }
1291 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001292 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001293 }
1294
1295 // Distance
1296 if (mRawPointerAxes.distance.valid) {
Michael Wright227c5542020-07-02 18:30:52 +01001297 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1298 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001299 }
1300 } else {
Michael Wright227c5542020-07-02 18:30:52 +01001301 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001302 }
1303
1304 // Coverage
Michael Wright227c5542020-07-02 18:30:52 +01001305 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1306 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001307 }
1308}
1309
1310void TouchInputMapper::dumpCalibration(std::string& dump) {
1311 dump += INDENT3 "Calibration:\n";
1312
1313 // Size
1314 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001315 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001316 dump += INDENT4 "touch.size.calibration: none\n";
1317 break;
Michael Wright227c5542020-07-02 18:30:52 +01001318 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001319 dump += INDENT4 "touch.size.calibration: geometric\n";
1320 break;
Michael Wright227c5542020-07-02 18:30:52 +01001321 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001322 dump += INDENT4 "touch.size.calibration: diameter\n";
1323 break;
Michael Wright227c5542020-07-02 18:30:52 +01001324 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001325 dump += INDENT4 "touch.size.calibration: box\n";
1326 break;
Michael Wright227c5542020-07-02 18:30:52 +01001327 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001328 dump += INDENT4 "touch.size.calibration: area\n";
1329 break;
1330 default:
1331 ALOG_ASSERT(false);
1332 }
1333
1334 if (mCalibration.haveSizeScale) {
1335 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1336 }
1337
1338 if (mCalibration.haveSizeBias) {
1339 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1340 }
1341
1342 if (mCalibration.haveSizeIsSummed) {
1343 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1344 toString(mCalibration.sizeIsSummed));
1345 }
1346
1347 // Pressure
1348 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001349 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001350 dump += INDENT4 "touch.pressure.calibration: none\n";
1351 break;
Michael Wright227c5542020-07-02 18:30:52 +01001352 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001353 dump += INDENT4 "touch.pressure.calibration: physical\n";
1354 break;
Michael Wright227c5542020-07-02 18:30:52 +01001355 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001356 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1357 break;
1358 default:
1359 ALOG_ASSERT(false);
1360 }
1361
1362 if (mCalibration.havePressureScale) {
1363 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1364 }
1365
1366 // Orientation
1367 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001368 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001369 dump += INDENT4 "touch.orientation.calibration: none\n";
1370 break;
Michael Wright227c5542020-07-02 18:30:52 +01001371 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001372 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1373 break;
Michael Wright227c5542020-07-02 18:30:52 +01001374 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001375 dump += INDENT4 "touch.orientation.calibration: vector\n";
1376 break;
1377 default:
1378 ALOG_ASSERT(false);
1379 }
1380
1381 // Distance
1382 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001383 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001384 dump += INDENT4 "touch.distance.calibration: none\n";
1385 break;
Michael Wright227c5542020-07-02 18:30:52 +01001386 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001387 dump += INDENT4 "touch.distance.calibration: scaled\n";
1388 break;
1389 default:
1390 ALOG_ASSERT(false);
1391 }
1392
1393 if (mCalibration.haveDistanceScale) {
1394 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1395 }
1396
1397 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01001398 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001399 dump += INDENT4 "touch.coverage.calibration: none\n";
1400 break;
Michael Wright227c5542020-07-02 18:30:52 +01001401 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001402 dump += INDENT4 "touch.coverage.calibration: box\n";
1403 break;
1404 default:
1405 ALOG_ASSERT(false);
1406 }
1407}
1408
1409void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1410 dump += INDENT3 "Affine Transformation:\n";
1411
1412 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1413 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1414 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1415 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1416 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1417 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1418}
1419
1420void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001421 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001422 mSurfaceOrientation);
1423}
1424
1425void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001426 mCursorButtonAccumulator.reset(getDeviceContext());
1427 mCursorScrollAccumulator.reset(getDeviceContext());
1428 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001429
1430 mPointerVelocityControl.reset();
1431 mWheelXVelocityControl.reset();
1432 mWheelYVelocityControl.reset();
1433
1434 mRawStatesPending.clear();
1435 mCurrentRawState.clear();
1436 mCurrentCookedState.clear();
1437 mLastRawState.clear();
1438 mLastCookedState.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001439 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001440 mSentHoverEnter = false;
1441 mHavePointerIds = false;
1442 mCurrentMotionAborted = false;
1443 mDownTime = 0;
1444
1445 mCurrentVirtualKey.down = false;
1446
1447 mPointerGesture.reset();
1448 mPointerSimple.reset();
1449 resetExternalStylus();
1450
1451 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01001452 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001453 mPointerController->clearSpots();
1454 }
1455
1456 InputMapper::reset(when);
1457}
1458
1459void TouchInputMapper::resetExternalStylus() {
1460 mExternalStylusState.clear();
1461 mExternalStylusId = -1;
1462 mExternalStylusFusionTimeout = LLONG_MAX;
1463 mExternalStylusDataPending = false;
1464}
1465
1466void TouchInputMapper::clearStylusDataPendingFlags() {
1467 mExternalStylusDataPending = false;
1468 mExternalStylusFusionTimeout = LLONG_MAX;
1469}
1470
1471void TouchInputMapper::process(const RawEvent* rawEvent) {
1472 mCursorButtonAccumulator.process(rawEvent);
1473 mCursorScrollAccumulator.process(rawEvent);
1474 mTouchButtonAccumulator.process(rawEvent);
1475
1476 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001477 sync(rawEvent->when, rawEvent->readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001478 }
1479}
1480
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001481void TouchInputMapper::sync(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001482 // Push a new state.
1483 mRawStatesPending.emplace_back();
1484
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001485 RawState& next = mRawStatesPending.back();
1486 next.clear();
1487 next.when = when;
1488 next.readTime = readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001489
1490 // Sync button state.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001491 next.buttonState =
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001492 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1493
1494 // Sync scroll
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001495 next.rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1496 next.rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001497 mCursorScrollAccumulator.finishSync();
1498
1499 // Sync touch
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001500 syncTouch(when, &next);
1501
1502 // The last RawState is the actually second to last, since we just added a new state
1503 const RawState& last =
1504 mRawStatesPending.size() == 1 ? mCurrentRawState : mRawStatesPending.rbegin()[1];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001505
1506 // Assign pointer ids.
1507 if (!mHavePointerIds) {
1508 assignPointerIds(last, next);
1509 }
1510
1511#if DEBUG_RAW_EVENTS
1512 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhungcc7f9802020-04-30 17:55:40 +08001513 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Siarhei Vishniakou57479982021-03-03 01:32:21 +00001514 last.rawPointerData.pointerCount, next.rawPointerData.pointerCount,
1515 last.rawPointerData.touchingIdBits.value, next.rawPointerData.touchingIdBits.value,
1516 last.rawPointerData.hoveringIdBits.value, next.rawPointerData.hoveringIdBits.value,
1517 next.rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001518#endif
1519
Arthur Hung9ad18942021-06-19 02:04:46 +00001520 if (!next.rawPointerData.touchingIdBits.isEmpty() &&
1521 !next.rawPointerData.hoveringIdBits.isEmpty() &&
1522 last.rawPointerData.hoveringIdBits != next.rawPointerData.hoveringIdBits) {
1523 ALOGI("Multi-touch contains some hovering ids 0x%08x",
1524 next.rawPointerData.hoveringIdBits.value);
1525 }
1526
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001527 processRawTouches(false /*timeout*/);
1528}
1529
1530void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001531 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001532 // Drop all input if the device is disabled.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001533 cancelTouch(mCurrentRawState.when, mCurrentRawState.readTime);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001534 mCurrentCookedState.clear();
1535 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001536 return;
1537 }
1538
1539 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1540 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1541 // touching the current state will only observe the events that have been dispatched to the
1542 // rest of the pipeline.
1543 const size_t N = mRawStatesPending.size();
1544 size_t count;
1545 for (count = 0; count < N; count++) {
1546 const RawState& next = mRawStatesPending[count];
1547
1548 // A failure to assign the stylus id means that we're waiting on stylus data
1549 // and so should defer the rest of the pipeline.
1550 if (assignExternalStylusId(next, timeout)) {
1551 break;
1552 }
1553
1554 // All ready to go.
1555 clearStylusDataPendingFlags();
1556 mCurrentRawState.copyFrom(next);
1557 if (mCurrentRawState.when < mLastRawState.when) {
1558 mCurrentRawState.when = mLastRawState.when;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001559 mCurrentRawState.readTime = mLastRawState.readTime;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001560 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001561 cookAndDispatch(mCurrentRawState.when, mCurrentRawState.readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001562 }
1563 if (count != 0) {
1564 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1565 }
1566
1567 if (mExternalStylusDataPending) {
1568 if (timeout) {
1569 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1570 clearStylusDataPendingFlags();
1571 mCurrentRawState.copyFrom(mLastRawState);
1572#if DEBUG_STYLUS_FUSION
1573 ALOGD("Timeout expired, synthesizing event with new stylus data");
1574#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001575 const nsecs_t readTime = when; // consider this synthetic event to be zero latency
1576 cookAndDispatch(when, readTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001577 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1578 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1579 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1580 }
1581 }
1582}
1583
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001584void TouchInputMapper::cookAndDispatch(nsecs_t when, nsecs_t readTime) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001585 // Always start with a clean state.
1586 mCurrentCookedState.clear();
1587
1588 // Apply stylus buttons to current raw state.
1589 applyExternalStylusButtonState(when);
1590
1591 // Handle policy on initial down or hover events.
1592 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1593 mCurrentRawState.rawPointerData.pointerCount != 0;
1594
1595 uint32_t policyFlags = 0;
1596 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1597 if (initialDown || buttonsPressed) {
1598 // If this is a touch screen, hide the pointer on an initial down.
Michael Wright227c5542020-07-02 18:30:52 +01001599 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001600 getContext()->fadePointer();
1601 }
1602
1603 if (mParameters.wake) {
1604 policyFlags |= POLICY_FLAG_WAKE;
1605 }
1606 }
1607
1608 // Consume raw off-screen touches before cooking pointer data.
1609 // If touches are consumed, subsequent code will not receive any pointer data.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001610 if (consumeRawTouches(when, readTime, policyFlags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001611 mCurrentRawState.rawPointerData.clear();
1612 }
1613
1614 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1615 // with cooked pointer data that has the same ids and indices as the raw data.
1616 // The following code can use either the raw or cooked data, as needed.
1617 cookPointerData();
1618
1619 // Apply stylus pressure to current cooked state.
1620 applyExternalStylusTouchState(when);
1621
1622 // Synthesize key down from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001623 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
1624 mSource, mViewport.displayId, policyFlags, mLastCookedState.buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001625 mCurrentCookedState.buttonState);
1626
1627 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wright227c5542020-07-02 18:30:52 +01001628 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001629 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1630 uint32_t id = idBits.clearFirstMarkedBit();
1631 const RawPointerData::Pointer& pointer =
1632 mCurrentRawState.rawPointerData.pointerForId(id);
1633 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1634 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1635 mCurrentCookedState.stylusIdBits.markBit(id);
1636 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1637 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1638 mCurrentCookedState.fingerIdBits.markBit(id);
1639 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1640 mCurrentCookedState.mouseIdBits.markBit(id);
1641 }
1642 }
1643 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1644 uint32_t id = idBits.clearFirstMarkedBit();
1645 const RawPointerData::Pointer& pointer =
1646 mCurrentRawState.rawPointerData.pointerForId(id);
1647 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1648 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1649 mCurrentCookedState.stylusIdBits.markBit(id);
1650 }
1651 }
1652
1653 // Stylus takes precedence over all tools, then mouse, then finger.
1654 PointerUsage pointerUsage = mPointerUsage;
1655 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1656 mCurrentCookedState.mouseIdBits.clear();
1657 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001658 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001659 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1660 mCurrentCookedState.fingerIdBits.clear();
Michael Wright227c5542020-07-02 18:30:52 +01001661 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001662 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1663 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wright227c5542020-07-02 18:30:52 +01001664 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001665 }
1666
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001667 dispatchPointerUsage(when, readTime, policyFlags, pointerUsage);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001668 } else {
Garfield Tanc734e4f2021-01-15 20:01:39 -08001669 updateTouchSpots();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001670
1671 if (!mCurrentMotionAborted) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001672 dispatchButtonRelease(when, readTime, policyFlags);
1673 dispatchHoverExit(when, readTime, policyFlags);
1674 dispatchTouches(when, readTime, policyFlags);
1675 dispatchHoverEnterAndMove(when, readTime, policyFlags);
1676 dispatchButtonPress(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001677 }
1678
1679 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1680 mCurrentMotionAborted = false;
1681 }
1682 }
1683
1684 // Synthesize key up from raw buttons if needed.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001685 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001686 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1687 mCurrentCookedState.buttonState);
1688
1689 // Clear some transient state.
1690 mCurrentRawState.rawVScroll = 0;
1691 mCurrentRawState.rawHScroll = 0;
1692
1693 // Copy current touch to last touch in preparation for the next cycle.
1694 mLastRawState.copyFrom(mCurrentRawState);
1695 mLastCookedState.copyFrom(mCurrentCookedState);
1696}
1697
Garfield Tanc734e4f2021-01-15 20:01:39 -08001698void TouchInputMapper::updateTouchSpots() {
1699 if (!mConfig.showTouches || mPointerController == nullptr) {
1700 return;
1701 }
1702
1703 // Update touch spots when this is a touchscreen even when it's not enabled so that we can
1704 // clear touch spots.
1705 if (mDeviceMode != DeviceMode::DIRECT &&
1706 (mDeviceMode != DeviceMode::DISABLED || !isTouchScreen())) {
1707 return;
1708 }
1709
1710 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1711 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
1712
1713 mPointerController->setButtonState(mCurrentRawState.buttonState);
Prabir Pradhand7482e72021-03-09 13:54:55 -08001714 setTouchSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1715 mCurrentCookedState.cookedPointerData.idToIndex,
1716 mCurrentCookedState.cookedPointerData.touchingIdBits, mViewport.displayId);
Garfield Tanc734e4f2021-01-15 20:01:39 -08001717}
1718
1719bool TouchInputMapper::isTouchScreen() {
1720 return mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
1721 mParameters.hasAssociatedDisplay;
1722}
1723
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001724void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001725 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001726 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1727 }
1728}
1729
1730void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1731 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1732 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1733
1734 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1735 float pressure = mExternalStylusState.pressure;
1736 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1737 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1738 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1739 }
1740 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1741 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1742
1743 PointerProperties& properties =
1744 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1745 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1746 properties.toolType = mExternalStylusState.toolType;
1747 }
1748 }
1749}
1750
1751bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wright227c5542020-07-02 18:30:52 +01001752 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001753 return false;
1754 }
1755
1756 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1757 state.rawPointerData.pointerCount != 0;
1758 if (initialDown) {
1759 if (mExternalStylusState.pressure != 0.0f) {
1760#if DEBUG_STYLUS_FUSION
1761 ALOGD("Have both stylus and touch data, beginning fusion");
1762#endif
1763 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1764 } else if (timeout) {
1765#if DEBUG_STYLUS_FUSION
1766 ALOGD("Timeout expired, assuming touch is not a stylus.");
1767#endif
1768 resetExternalStylus();
1769 } else {
1770 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1771 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1772 }
1773#if DEBUG_STYLUS_FUSION
1774 ALOGD("No stylus data but stylus is connected, requesting timeout "
1775 "(%" PRId64 "ms)",
1776 mExternalStylusFusionTimeout);
1777#endif
1778 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1779 return true;
1780 }
1781 }
1782
1783 // Check if the stylus pointer has gone up.
1784 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1785#if DEBUG_STYLUS_FUSION
1786 ALOGD("Stylus pointer is going up");
1787#endif
1788 mExternalStylusId = -1;
1789 }
1790
1791 return false;
1792}
1793
1794void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wright227c5542020-07-02 18:30:52 +01001795 if (mDeviceMode == DeviceMode::POINTER) {
1796 if (mPointerUsage == PointerUsage::GESTURES) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001797 // Since this is a synthetic event, we can consider its latency to be zero
1798 const nsecs_t readTime = when;
1799 dispatchPointerGestures(when, readTime, 0 /*policyFlags*/, true /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001800 }
Michael Wright227c5542020-07-02 18:30:52 +01001801 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001802 if (mExternalStylusFusionTimeout < when) {
1803 processRawTouches(true /*timeout*/);
1804 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1805 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1806 }
1807 }
1808}
1809
1810void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1811 mExternalStylusState.copyFrom(state);
1812 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1813 // We're either in the middle of a fused stream of data or we're waiting on data before
1814 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1815 // data.
1816 mExternalStylusDataPending = true;
1817 processRawTouches(false /*timeout*/);
1818 }
1819}
1820
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001821bool TouchInputMapper::consumeRawTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001822 // Check for release of a virtual key.
1823 if (mCurrentVirtualKey.down) {
1824 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1825 // Pointer went up while virtual key was down.
1826 mCurrentVirtualKey.down = false;
1827 if (!mCurrentVirtualKey.ignored) {
1828#if DEBUG_VIRTUAL_KEYS
1829 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1830 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1831#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001832 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001833 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1834 }
1835 return true;
1836 }
1837
1838 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1839 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1840 const RawPointerData::Pointer& pointer =
1841 mCurrentRawState.rawPointerData.pointerForId(id);
1842 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1843 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1844 // Pointer is still within the space of the virtual key.
1845 return true;
1846 }
1847 }
1848
1849 // Pointer left virtual key area or another pointer also went down.
1850 // Send key cancellation but do not consume the touch yet.
1851 // This is useful when the user swipes through from the virtual key area
1852 // into the main display surface.
1853 mCurrentVirtualKey.down = false;
1854 if (!mCurrentVirtualKey.ignored) {
1855#if DEBUG_VIRTUAL_KEYS
1856 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1857 mCurrentVirtualKey.scanCode);
1858#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001859 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_UP,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001860 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1861 AKEY_EVENT_FLAG_CANCELED);
1862 }
1863 }
1864
1865 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1866 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1867 // Pointer just went down. Check for virtual key press or off-screen touches.
1868 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1869 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Ye364fdb52020-08-05 15:07:56 -07001870 // Exclude unscaled device for inside surface checking.
1871 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001872 // If exactly one pointer went down, check for virtual key hit.
1873 // Otherwise we will drop the entire stroke.
1874 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1875 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1876 if (virtualKey) {
1877 mCurrentVirtualKey.down = true;
1878 mCurrentVirtualKey.downTime = when;
1879 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1880 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1881 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001882 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1883 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001884
1885 if (!mCurrentVirtualKey.ignored) {
1886#if DEBUG_VIRTUAL_KEYS
1887 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1888 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1889#endif
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001890 dispatchVirtualKey(when, readTime, policyFlags, AKEY_EVENT_ACTION_DOWN,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001891 AKEY_EVENT_FLAG_FROM_SYSTEM |
1892 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1893 }
1894 }
1895 }
1896 return true;
1897 }
1898 }
1899
1900 // Disable all virtual key touches that happen within a short time interval of the
1901 // most recent touch within the screen area. The idea is to filter out stray
1902 // virtual key presses when interacting with the touch screen.
1903 //
1904 // Problems we're trying to solve:
1905 //
1906 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1907 // virtual key area that is implemented by a separate touch panel and accidentally
1908 // triggers a virtual key.
1909 //
1910 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1911 // area and accidentally triggers a virtual key. This often happens when virtual keys
1912 // are layed out below the screen near to where the on screen keyboard's space bar
1913 // is displayed.
1914 if (mConfig.virtualKeyQuietTime > 0 &&
1915 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001916 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001917 }
1918 return false;
1919}
1920
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001921void TouchInputMapper::dispatchVirtualKey(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001922 int32_t keyEventAction, int32_t keyEventFlags) {
1923 int32_t keyCode = mCurrentVirtualKey.keyCode;
1924 int32_t scanCode = mCurrentVirtualKey.scanCode;
1925 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001926 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001927 policyFlags |= POLICY_FLAG_VIRTUAL;
1928
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001929 NotifyKeyArgs args(getContext()->getNextId(), when, readTime, getDeviceId(),
1930 AINPUT_SOURCE_KEYBOARD, mViewport.displayId, policyFlags, keyEventAction,
1931 keyEventFlags, keyCode, scanCode, metaState, downTime);
Siarhei Vishniakou18050092021-09-01 13:32:49 -07001932 getListener().notifyKey(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001933}
1934
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001935void TouchInputMapper::abortTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001936 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1937 if (!currentIdBits.isEmpty()) {
1938 int32_t metaState = getContext()->getGlobalMetaState();
1939 int32_t buttonState = mCurrentCookedState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001940 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
1941 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001942 mCurrentCookedState.cookedPointerData.pointerProperties,
1943 mCurrentCookedState.cookedPointerData.pointerCoords,
1944 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1945 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1946 mCurrentMotionAborted = true;
1947 }
1948}
1949
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001950void TouchInputMapper::dispatchTouches(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001951 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1952 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1953 int32_t metaState = getContext()->getGlobalMetaState();
1954 int32_t buttonState = mCurrentCookedState.buttonState;
1955
1956 if (currentIdBits == lastIdBits) {
1957 if (!currentIdBits.isEmpty()) {
1958 // No pointer id changes so this is a move event.
1959 // The listener takes care of batching moves so we don't have to deal with that here.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001960 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
1961 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001962 mCurrentCookedState.cookedPointerData.pointerProperties,
1963 mCurrentCookedState.cookedPointerData.pointerCoords,
1964 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1965 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1966 }
1967 } else {
1968 // There may be pointers going up and pointers going down and pointers moving
1969 // all at the same time.
1970 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1971 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1972 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1973 BitSet32 dispatchedIdBits(lastIdBits.value);
1974
1975 // Update last coordinates of pointers that have moved so that we observe the new
1976 // pointer positions at the same time as other pointers that have just gone up.
1977 bool moveNeeded =
1978 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1979 mCurrentCookedState.cookedPointerData.pointerCoords,
1980 mCurrentCookedState.cookedPointerData.idToIndex,
1981 mLastCookedState.cookedPointerData.pointerProperties,
1982 mLastCookedState.cookedPointerData.pointerCoords,
1983 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1984 if (buttonState != mLastCookedState.buttonState) {
1985 moveNeeded = true;
1986 }
1987
1988 // Dispatch pointer up events.
1989 while (!upIdBits.isEmpty()) {
1990 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhungcc7f9802020-04-30 17:55:40 +08001991 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
arthurhung17d64842021-01-21 16:01:27 +08001992 if (isCanceled) {
1993 ALOGI("Canceling pointer %d for the palm event was detected.", upId);
1994 }
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00001995 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
arthurhungcc7f9802020-04-30 17:55:40 +08001996 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001997 mLastCookedState.cookedPointerData.pointerProperties,
1998 mLastCookedState.cookedPointerData.pointerCoords,
1999 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
2000 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2001 dispatchedIdBits.clearBit(upId);
arthurhungcc7f9802020-04-30 17:55:40 +08002002 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002003 }
2004
2005 // Dispatch move events if any of the remaining pointers moved from their old locations.
2006 // Although applications receive new locations as part of individual pointer up
2007 // events, they do not generally handle them except when presented in a move event.
2008 if (moveNeeded && !moveIdBits.isEmpty()) {
2009 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002010 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0,
2011 metaState, buttonState, 0,
2012 mCurrentCookedState.cookedPointerData.pointerProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002013 mCurrentCookedState.cookedPointerData.pointerCoords,
2014 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
2015 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2016 }
2017
2018 // Dispatch pointer down events using the new pointer locations.
2019 while (!downIdBits.isEmpty()) {
2020 uint32_t downId = downIdBits.clearFirstMarkedBit();
2021 dispatchedIdBits.markBit(downId);
2022
2023 if (dispatchedIdBits.count() == 1) {
2024 // First pointer is going down. Set down time.
2025 mDownTime = when;
2026 }
2027
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002028 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
2029 0, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002030 mCurrentCookedState.cookedPointerData.pointerProperties,
2031 mCurrentCookedState.cookedPointerData.pointerCoords,
2032 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
2033 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2034 }
2035 }
2036}
2037
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002038void TouchInputMapper::dispatchHoverExit(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002039 if (mSentHoverEnter &&
2040 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
2041 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
2042 int32_t metaState = getContext()->getGlobalMetaState();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002043 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
2044 metaState, mLastCookedState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002045 mLastCookedState.cookedPointerData.pointerProperties,
2046 mLastCookedState.cookedPointerData.pointerCoords,
2047 mLastCookedState.cookedPointerData.idToIndex,
2048 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
2049 mOrientedYPrecision, mDownTime);
2050 mSentHoverEnter = false;
2051 }
2052}
2053
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002054void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, nsecs_t readTime,
2055 uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002056 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
2057 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
2058 int32_t metaState = getContext()->getGlobalMetaState();
2059 if (!mSentHoverEnter) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002060 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER,
2061 0, 0, metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002062 mCurrentCookedState.cookedPointerData.pointerProperties,
2063 mCurrentCookedState.cookedPointerData.pointerCoords,
2064 mCurrentCookedState.cookedPointerData.idToIndex,
2065 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2066 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2067 mSentHoverEnter = true;
2068 }
2069
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002070 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
2071 metaState, mCurrentRawState.buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002072 mCurrentCookedState.cookedPointerData.pointerProperties,
2073 mCurrentCookedState.cookedPointerData.pointerCoords,
2074 mCurrentCookedState.cookedPointerData.idToIndex,
2075 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2076 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2077 }
2078}
2079
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002080void TouchInputMapper::dispatchButtonRelease(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002081 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2082 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2083 const int32_t metaState = getContext()->getGlobalMetaState();
2084 int32_t buttonState = mLastCookedState.buttonState;
2085 while (!releasedButtons.isEmpty()) {
2086 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2087 buttonState &= ~actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002088 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002089 actionButton, 0, metaState, buttonState, 0,
2090 mCurrentCookedState.cookedPointerData.pointerProperties,
2091 mCurrentCookedState.cookedPointerData.pointerCoords,
2092 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2093 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2094 }
2095}
2096
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002097void TouchInputMapper::dispatchButtonPress(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002098 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2099 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2100 const int32_t metaState = getContext()->getGlobalMetaState();
2101 int32_t buttonState = mLastCookedState.buttonState;
2102 while (!pressedButtons.isEmpty()) {
2103 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2104 buttonState |= actionButton;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002105 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS,
2106 actionButton, 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002107 mCurrentCookedState.cookedPointerData.pointerProperties,
2108 mCurrentCookedState.cookedPointerData.pointerCoords,
2109 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2110 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2111 }
2112}
2113
2114const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2115 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2116 return cookedPointerData.touchingIdBits;
2117 }
2118 return cookedPointerData.hoveringIdBits;
2119}
2120
2121void TouchInputMapper::cookPointerData() {
2122 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2123
2124 mCurrentCookedState.cookedPointerData.clear();
2125 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2126 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2127 mCurrentRawState.rawPointerData.hoveringIdBits;
2128 mCurrentCookedState.cookedPointerData.touchingIdBits =
2129 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhungcc7f9802020-04-30 17:55:40 +08002130 mCurrentCookedState.cookedPointerData.canceledIdBits =
2131 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002132
2133 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2134 mCurrentCookedState.buttonState = 0;
2135 } else {
2136 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2137 }
2138
2139 // Walk through the the active pointers and map device coordinates onto
2140 // surface coordinates and adjust for display orientation.
2141 for (uint32_t i = 0; i < currentPointerCount; i++) {
2142 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2143
2144 // Size
2145 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2146 switch (mCalibration.sizeCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002147 case Calibration::SizeCalibration::GEOMETRIC:
2148 case Calibration::SizeCalibration::DIAMETER:
2149 case Calibration::SizeCalibration::BOX:
2150 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002151 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2152 touchMajor = in.touchMajor;
2153 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2154 toolMajor = in.toolMajor;
2155 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2156 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2157 : in.touchMajor;
2158 } else if (mRawPointerAxes.touchMajor.valid) {
2159 toolMajor = touchMajor = in.touchMajor;
2160 toolMinor = touchMinor =
2161 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2162 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2163 : in.touchMajor;
2164 } else if (mRawPointerAxes.toolMajor.valid) {
2165 touchMajor = toolMajor = in.toolMajor;
2166 touchMinor = toolMinor =
2167 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2168 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2169 : in.toolMajor;
2170 } else {
2171 ALOG_ASSERT(false,
2172 "No touch or tool axes. "
2173 "Size calibration should have been resolved to NONE.");
2174 touchMajor = 0;
2175 touchMinor = 0;
2176 toolMajor = 0;
2177 toolMinor = 0;
2178 size = 0;
2179 }
2180
2181 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2182 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2183 if (touchingCount > 1) {
2184 touchMajor /= touchingCount;
2185 touchMinor /= touchingCount;
2186 toolMajor /= touchingCount;
2187 toolMinor /= touchingCount;
2188 size /= touchingCount;
2189 }
2190 }
2191
Michael Wright227c5542020-07-02 18:30:52 +01002192 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002193 touchMajor *= mGeometricScale;
2194 touchMinor *= mGeometricScale;
2195 toolMajor *= mGeometricScale;
2196 toolMinor *= mGeometricScale;
Michael Wright227c5542020-07-02 18:30:52 +01002197 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002198 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2199 touchMinor = touchMajor;
2200 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2201 toolMinor = toolMajor;
Michael Wright227c5542020-07-02 18:30:52 +01002202 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002203 touchMinor = touchMajor;
2204 toolMinor = toolMajor;
2205 }
2206
2207 mCalibration.applySizeScaleAndBias(&touchMajor);
2208 mCalibration.applySizeScaleAndBias(&touchMinor);
2209 mCalibration.applySizeScaleAndBias(&toolMajor);
2210 mCalibration.applySizeScaleAndBias(&toolMinor);
2211 size *= mSizeScale;
2212 break;
2213 default:
2214 touchMajor = 0;
2215 touchMinor = 0;
2216 toolMajor = 0;
2217 toolMinor = 0;
2218 size = 0;
2219 break;
2220 }
2221
2222 // Pressure
2223 float pressure;
2224 switch (mCalibration.pressureCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002225 case Calibration::PressureCalibration::PHYSICAL:
2226 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002227 pressure = in.pressure * mPressureScale;
2228 break;
2229 default:
2230 pressure = in.isHovering ? 0 : 1;
2231 break;
2232 }
2233
2234 // Tilt and Orientation
2235 float tilt;
2236 float orientation;
2237 if (mHaveTilt) {
2238 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2239 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2240 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2241 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2242 } else {
2243 tilt = 0;
2244
2245 switch (mCalibration.orientationCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002246 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002247 orientation = in.orientation * mOrientationScale;
2248 break;
Michael Wright227c5542020-07-02 18:30:52 +01002249 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002250 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2251 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2252 if (c1 != 0 || c2 != 0) {
2253 orientation = atan2f(c1, c2) * 0.5f;
2254 float confidence = hypotf(c1, c2);
2255 float scale = 1.0f + confidence / 16.0f;
2256 touchMajor *= scale;
2257 touchMinor /= scale;
2258 toolMajor *= scale;
2259 toolMinor /= scale;
2260 } else {
2261 orientation = 0;
2262 }
2263 break;
2264 }
2265 default:
2266 orientation = 0;
2267 }
2268 }
2269
2270 // Distance
2271 float distance;
2272 switch (mCalibration.distanceCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002273 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002274 distance = in.distance * mDistanceScale;
2275 break;
2276 default:
2277 distance = 0;
2278 }
2279
2280 // Coverage
2281 int32_t rawLeft, rawTop, rawRight, rawBottom;
2282 switch (mCalibration.coverageCalibration) {
Michael Wright227c5542020-07-02 18:30:52 +01002283 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002284 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2285 rawRight = in.toolMinor & 0x0000ffff;
2286 rawBottom = in.toolMajor & 0x0000ffff;
2287 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2288 break;
2289 default:
2290 rawLeft = rawTop = rawRight = rawBottom = 0;
2291 break;
2292 }
2293
2294 // Adjust X,Y coords for device calibration
2295 // TODO: Adjust coverage coords?
2296 float xTransformed = in.x, yTransformed = in.y;
2297 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002298 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002299
2300 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002301 float left, top, right, bottom;
2302
2303 switch (mSurfaceOrientation) {
2304 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002305 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2306 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2307 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2308 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2309 orientation -= M_PI_2;
2310 if (mOrientedRanges.haveOrientation &&
2311 orientation < mOrientedRanges.orientation.min) {
2312 orientation +=
2313 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2314 }
2315 break;
2316 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002317 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2318 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2319 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2320 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2321 orientation -= M_PI;
2322 if (mOrientedRanges.haveOrientation &&
2323 orientation < mOrientedRanges.orientation.min) {
2324 orientation +=
2325 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2326 }
2327 break;
2328 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002329 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2330 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2331 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2332 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2333 orientation += M_PI_2;
2334 if (mOrientedRanges.haveOrientation &&
2335 orientation > mOrientedRanges.orientation.max) {
2336 orientation -=
2337 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2338 }
2339 break;
2340 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002341 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2342 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2343 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2344 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2345 break;
2346 }
2347
2348 // Write output coords.
2349 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2350 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002351 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2352 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002353 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2354 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2355 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2356 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2357 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2358 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2359 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wright227c5542020-07-02 18:30:52 +01002360 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002361 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2362 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2363 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2364 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2365 } else {
2366 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2367 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2368 }
2369
Chris Ye364fdb52020-08-05 15:07:56 -07002370 // Write output relative fields if applicable.
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002371 uint32_t id = in.id;
2372 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2373 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2374 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2375 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2376 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2377 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2378 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2379 }
2380
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002381 // Write output properties.
2382 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002383 properties.clear();
2384 properties.id = id;
2385 properties.toolType = in.toolType;
2386
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002387 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002388 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewisadb58ea2019-08-21 04:46:29 +00002389 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002390 }
2391}
2392
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002393void TouchInputMapper::dispatchPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002394 PointerUsage pointerUsage) {
2395 if (pointerUsage != mPointerUsage) {
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002396 abortPointerUsage(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002397 mPointerUsage = pointerUsage;
2398 }
2399
2400 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002401 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002402 dispatchPointerGestures(when, readTime, policyFlags, false /*isTimeout*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002403 break;
Michael Wright227c5542020-07-02 18:30:52 +01002404 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002405 dispatchPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002406 break;
Michael Wright227c5542020-07-02 18:30:52 +01002407 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002408 dispatchPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002409 break;
Michael Wright227c5542020-07-02 18:30:52 +01002410 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002411 break;
2412 }
2413}
2414
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002415void TouchInputMapper::abortPointerUsage(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002416 switch (mPointerUsage) {
Michael Wright227c5542020-07-02 18:30:52 +01002417 case PointerUsage::GESTURES:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002418 abortPointerGestures(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002419 break;
Michael Wright227c5542020-07-02 18:30:52 +01002420 case PointerUsage::STYLUS:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002421 abortPointerStylus(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002422 break;
Michael Wright227c5542020-07-02 18:30:52 +01002423 case PointerUsage::MOUSE:
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002424 abortPointerMouse(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002425 break;
Michael Wright227c5542020-07-02 18:30:52 +01002426 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002427 break;
2428 }
2429
Michael Wright227c5542020-07-02 18:30:52 +01002430 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002431}
2432
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002433void TouchInputMapper::dispatchPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
2434 bool isTimeout) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002435 // Update current gesture coordinates.
2436 bool cancelPreviousGesture, finishPreviousGesture;
2437 bool sendEvents =
2438 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2439 if (!sendEvents) {
2440 return;
2441 }
2442 if (finishPreviousGesture) {
2443 cancelPreviousGesture = false;
2444 }
2445
2446 // Update the pointer presentation and spots.
Michael Wright227c5542020-07-02 18:30:52 +01002447 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002448 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002449 if (finishPreviousGesture || cancelPreviousGesture) {
2450 mPointerController->clearSpots();
2451 }
2452
Michael Wright227c5542020-07-02 18:30:52 +01002453 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002454 setTouchSpots(mPointerGesture.currentGestureCoords,
2455 mPointerGesture.currentGestureIdToIndex,
2456 mPointerGesture.currentGestureIdBits, mPointerController->getDisplayId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002457 }
2458 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002459 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002460 }
2461
2462 // Show or hide the pointer if needed.
2463 switch (mPointerGesture.currentGestureMode) {
Michael Wright227c5542020-07-02 18:30:52 +01002464 case PointerGesture::Mode::NEUTRAL:
2465 case PointerGesture::Mode::QUIET:
2466 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2467 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002468 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wrightca5bede2020-07-02 00:00:29 +01002469 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002470 }
2471 break;
Michael Wright227c5542020-07-02 18:30:52 +01002472 case PointerGesture::Mode::TAP:
2473 case PointerGesture::Mode::TAP_DRAG:
2474 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2475 case PointerGesture::Mode::HOVER:
2476 case PointerGesture::Mode::PRESS:
2477 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002478 // Unfade the pointer when the current gesture manipulates the
2479 // area directly under the pointer.
Michael Wrightca5bede2020-07-02 00:00:29 +01002480 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002481 break;
Michael Wright227c5542020-07-02 18:30:52 +01002482 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002483 // Fade the pointer when the current gesture manipulates a different
2484 // area and there are spots to guide the user experience.
Michael Wright227c5542020-07-02 18:30:52 +01002485 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002486 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002487 } else {
Michael Wrightca5bede2020-07-02 00:00:29 +01002488 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002489 }
2490 break;
2491 }
2492
2493 // Send events!
2494 int32_t metaState = getContext()->getGlobalMetaState();
2495 int32_t buttonState = mCurrentCookedState.buttonState;
2496
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002497 uint32_t flags = 0;
2498
2499 if (!PointerGesture::canGestureAffectWindowFocus(mPointerGesture.currentGestureMode)) {
2500 flags |= AMOTION_EVENT_FLAG_NO_FOCUS_CHANGE;
2501 }
2502
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002503 // Update last coordinates of pointers that have moved so that we observe the new
2504 // pointer positions at the same time as other pointers that have just gone up.
Michael Wright227c5542020-07-02 18:30:52 +01002505 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2506 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2507 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2508 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2509 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2510 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002511 bool moveNeeded = false;
2512 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2513 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2514 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2515 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2516 mPointerGesture.lastGestureIdBits.value);
2517 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2518 mPointerGesture.currentGestureCoords,
2519 mPointerGesture.currentGestureIdToIndex,
2520 mPointerGesture.lastGestureProperties,
2521 mPointerGesture.lastGestureCoords,
2522 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2523 if (buttonState != mLastCookedState.buttonState) {
2524 moveNeeded = true;
2525 }
2526 }
2527
2528 // Send motion events for all pointers that went up or were canceled.
2529 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2530 if (!dispatchedGestureIdBits.isEmpty()) {
2531 if (cancelPreviousGesture) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002532 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0,
2533 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002534 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2535 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2536 mPointerGesture.downTime);
2537
2538 dispatchedGestureIdBits.clear();
2539 } else {
2540 BitSet32 upGestureIdBits;
2541 if (finishPreviousGesture) {
2542 upGestureIdBits = dispatchedGestureIdBits;
2543 } else {
2544 upGestureIdBits.value =
2545 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2546 }
2547 while (!upGestureIdBits.isEmpty()) {
2548 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2549
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002550 dispatchMotion(when, readTime, policyFlags, mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002551 AMOTION_EVENT_ACTION_POINTER_UP, 0, flags, metaState, buttonState,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002552 AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002553 mPointerGesture.lastGestureCoords,
2554 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2555 0, mPointerGesture.downTime);
2556
2557 dispatchedGestureIdBits.clearBit(id);
2558 }
2559 }
2560 }
2561
2562 // Send motion events for all pointers that moved.
2563 if (moveNeeded) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002564 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002565 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002566 mPointerGesture.currentGestureProperties,
2567 mPointerGesture.currentGestureCoords,
2568 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2569 mPointerGesture.downTime);
2570 }
2571
2572 // Send motion events for all pointers that went down.
2573 if (down) {
2574 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2575 ~dispatchedGestureIdBits.value);
2576 while (!downGestureIdBits.isEmpty()) {
2577 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2578 dispatchedGestureIdBits.markBit(id);
2579
2580 if (dispatchedGestureIdBits.count() == 1) {
2581 mPointerGesture.downTime = when;
2582 }
2583
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002584 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002585 0, flags, metaState, buttonState, 0,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002586 mPointerGesture.currentGestureProperties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002587 mPointerGesture.currentGestureCoords,
2588 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2589 0, mPointerGesture.downTime);
2590 }
2591 }
2592
2593 // Send motion events for hover.
Michael Wright227c5542020-07-02 18:30:52 +01002594 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002595 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0,
2596 flags, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002597 mPointerGesture.currentGestureProperties,
2598 mPointerGesture.currentGestureCoords,
2599 mPointerGesture.currentGestureIdToIndex,
2600 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2601 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2602 // Synthesize a hover move event after all pointers go up to indicate that
2603 // the pointer is hovering again even if the user is not currently touching
2604 // the touch pad. This ensures that a view will receive a fresh hover enter
2605 // event after a tap.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002606 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002607
2608 PointerProperties pointerProperties;
2609 pointerProperties.clear();
2610 pointerProperties.id = 0;
2611 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2612
2613 PointerCoords pointerCoords;
2614 pointerCoords.clear();
2615 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2616 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2617
2618 const int32_t displayId = mPointerController->getDisplayId();
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002619 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Prabir Pradhan47cf0a02021-03-11 20:30:57 -08002620 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, flags,
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002621 metaState, buttonState, MotionClassification::NONE,
2622 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
2623 0, 0, x, y, mPointerGesture.downTime, /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07002624 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002625 }
2626
2627 // Update state.
2628 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2629 if (!down) {
2630 mPointerGesture.lastGestureIdBits.clear();
2631 } else {
2632 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2633 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2634 uint32_t id = idBits.clearFirstMarkedBit();
2635 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2636 mPointerGesture.lastGestureProperties[index].copyFrom(
2637 mPointerGesture.currentGestureProperties[index]);
2638 mPointerGesture.lastGestureCoords[index].copyFrom(
2639 mPointerGesture.currentGestureCoords[index]);
2640 mPointerGesture.lastGestureIdToIndex[id] = index;
2641 }
2642 }
2643}
2644
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002645void TouchInputMapper::abortPointerGestures(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002646 // Cancel previously dispatches pointers.
2647 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2648 int32_t metaState = getContext()->getGlobalMetaState();
2649 int32_t buttonState = mCurrentRawState.buttonState;
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00002650 dispatchMotion(when, readTime, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0,
2651 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002652 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2653 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2654 0, 0, mPointerGesture.downTime);
2655 }
2656
2657 // Reset the current pointer gesture.
2658 mPointerGesture.reset();
2659 mPointerVelocityControl.reset();
2660
2661 // Remove any current spots.
2662 if (mPointerController != nullptr) {
Michael Wrightca5bede2020-07-02 00:00:29 +01002663 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002664 mPointerController->clearSpots();
2665 }
2666}
2667
2668bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2669 bool* outFinishPreviousGesture, bool isTimeout) {
2670 *outCancelPreviousGesture = false;
2671 *outFinishPreviousGesture = false;
2672
2673 // Handle TAP timeout.
2674 if (isTimeout) {
2675#if DEBUG_GESTURES
2676 ALOGD("Gestures: Processing timeout");
2677#endif
2678
Michael Wright227c5542020-07-02 18:30:52 +01002679 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002680 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2681 // The tap/drag timeout has not yet expired.
2682 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2683 mConfig.pointerGestureTapDragInterval);
2684 } else {
2685 // The tap is finished.
2686#if DEBUG_GESTURES
2687 ALOGD("Gestures: TAP finished");
2688#endif
2689 *outFinishPreviousGesture = true;
2690
2691 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002692 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002693 mPointerGesture.currentGestureIdBits.clear();
2694
2695 mPointerVelocityControl.reset();
2696 return true;
2697 }
2698 }
2699
2700 // We did not handle this timeout.
2701 return false;
2702 }
2703
2704 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2705 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2706
2707 // Update the velocity tracker.
2708 {
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002709 std::vector<VelocityTracker::Position> positions;
2710 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002711 uint32_t id = idBits.clearFirstMarkedBit();
2712 const RawPointerData::Pointer& pointer =
2713 mCurrentRawState.rawPointerData.pointerForId(id);
Siarhei Vishniakouae0f9902020-09-14 19:23:31 -05002714 float x = pointer.x * mPointerXMovementScale;
2715 float y = pointer.y * mPointerYMovementScale;
2716 positions.push_back({x, y});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002717 }
2718 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2719 positions);
2720 }
2721
2722 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2723 // to NEUTRAL, then we should not generate tap event.
Michael Wright227c5542020-07-02 18:30:52 +01002724 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2725 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2726 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002727 mPointerGesture.resetTap();
2728 }
2729
2730 // Pick a new active touch id if needed.
2731 // Choose an arbitrary pointer that just went down, if there is one.
2732 // Otherwise choose an arbitrary remaining pointer.
2733 // This guarantees we always have an active touch id when there is at least one pointer.
2734 // We keep the same active touch id for as long as possible.
2735 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2736 int32_t activeTouchId = lastActiveTouchId;
2737 if (activeTouchId < 0) {
2738 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2739 activeTouchId = mPointerGesture.activeTouchId =
2740 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2741 mPointerGesture.firstTouchTime = when;
2742 }
2743 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2744 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2745 activeTouchId = mPointerGesture.activeTouchId =
2746 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2747 } else {
2748 activeTouchId = mPointerGesture.activeTouchId = -1;
2749 }
2750 }
2751
2752 // Determine whether we are in quiet time.
2753 bool isQuietTime = false;
2754 if (activeTouchId < 0) {
2755 mPointerGesture.resetQuietTime();
2756 } else {
2757 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2758 if (!isQuietTime) {
Michael Wright227c5542020-07-02 18:30:52 +01002759 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2760 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2761 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002762 currentFingerCount < 2) {
2763 // Enter quiet time when exiting swipe or freeform state.
2764 // This is to prevent accidentally entering the hover state and flinging the
2765 // pointer when finishing a swipe and there is still one pointer left onscreen.
2766 isQuietTime = true;
Michael Wright227c5542020-07-02 18:30:52 +01002767 } else if (mPointerGesture.lastGestureMode ==
2768 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002769 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2770 // Enter quiet time when releasing the button and there are still two or more
2771 // fingers down. This may indicate that one finger was used to press the button
2772 // but it has not gone up yet.
2773 isQuietTime = true;
2774 }
2775 if (isQuietTime) {
2776 mPointerGesture.quietTime = when;
2777 }
2778 }
2779 }
2780
2781 // Switch states based on button and pointer state.
2782 if (isQuietTime) {
2783 // Case 1: Quiet time. (QUIET)
2784#if DEBUG_GESTURES
2785 ALOGD("Gestures: QUIET for next %0.3fms",
2786 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2787#endif
Michael Wright227c5542020-07-02 18:30:52 +01002788 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002789 *outFinishPreviousGesture = true;
2790 }
2791
2792 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002793 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002794 mPointerGesture.currentGestureIdBits.clear();
2795
2796 mPointerVelocityControl.reset();
2797 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2798 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2799 // The pointer follows the active touch point.
2800 // Emit DOWN, MOVE, UP events at the pointer location.
2801 //
2802 // Only the active touch matters; other fingers are ignored. This policy helps
2803 // to handle the case where the user places a second finger on the touch pad
2804 // to apply the necessary force to depress an integrated button below the surface.
2805 // We don't want the second finger to be delivered to applications.
2806 //
2807 // For this to work well, we need to make sure to track the pointer that is really
2808 // active. If the user first puts one finger down to click then adds another
2809 // finger to drag then the active pointer should switch to the finger that is
2810 // being dragged.
2811#if DEBUG_GESTURES
2812 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2813 "currentFingerCount=%d",
2814 activeTouchId, currentFingerCount);
2815#endif
2816 // Reset state when just starting.
Michael Wright227c5542020-07-02 18:30:52 +01002817 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002818 *outFinishPreviousGesture = true;
2819 mPointerGesture.activeGestureId = 0;
2820 }
2821
2822 // Switch pointers if needed.
2823 // Find the fastest pointer and follow it.
2824 if (activeTouchId >= 0 && currentFingerCount > 1) {
2825 int32_t bestId = -1;
2826 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2827 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2828 uint32_t id = idBits.clearFirstMarkedBit();
2829 float vx, vy;
2830 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2831 float speed = hypotf(vx, vy);
2832 if (speed > bestSpeed) {
2833 bestId = id;
2834 bestSpeed = speed;
2835 }
2836 }
2837 }
2838 if (bestId >= 0 && bestId != activeTouchId) {
2839 mPointerGesture.activeTouchId = activeTouchId = bestId;
2840#if DEBUG_GESTURES
2841 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2842 "bestId=%d, bestSpeed=%0.3f",
2843 bestId, bestSpeed);
2844#endif
2845 }
2846 }
2847
2848 float deltaX = 0, deltaY = 0;
2849 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2850 const RawPointerData::Pointer& currentPointer =
2851 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2852 const RawPointerData::Pointer& lastPointer =
2853 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2854 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2855 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2856
2857 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2858 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2859
2860 // Move the pointer using a relative motion.
2861 // When using spots, the click will occur at the position of the anchor
2862 // spot and all other spots will move there.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002863 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002864 } else {
2865 mPointerVelocityControl.reset();
2866 }
2867
Prabir Pradhand7482e72021-03-09 13:54:55 -08002868 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002869
Michael Wright227c5542020-07-02 18:30:52 +01002870 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002871 mPointerGesture.currentGestureIdBits.clear();
2872 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2873 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2874 mPointerGesture.currentGestureProperties[0].clear();
2875 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2876 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2877 mPointerGesture.currentGestureCoords[0].clear();
2878 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2879 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2880 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2881 } else if (currentFingerCount == 0) {
2882 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wright227c5542020-07-02 18:30:52 +01002883 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002884 *outFinishPreviousGesture = true;
2885 }
2886
2887 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2888 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2889 bool tapped = false;
Michael Wright227c5542020-07-02 18:30:52 +01002890 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2891 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002892 lastFingerCount == 1) {
2893 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002894 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002895 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2896 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2897#if DEBUG_GESTURES
2898 ALOGD("Gestures: TAP");
2899#endif
2900
2901 mPointerGesture.tapUpTime = when;
2902 getContext()->requestTimeoutAtTime(when +
2903 mConfig.pointerGestureTapDragInterval);
2904
2905 mPointerGesture.activeGestureId = 0;
Michael Wright227c5542020-07-02 18:30:52 +01002906 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002907 mPointerGesture.currentGestureIdBits.clear();
2908 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2909 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2910 mPointerGesture.currentGestureProperties[0].clear();
2911 mPointerGesture.currentGestureProperties[0].id =
2912 mPointerGesture.activeGestureId;
2913 mPointerGesture.currentGestureProperties[0].toolType =
2914 AMOTION_EVENT_TOOL_TYPE_FINGER;
2915 mPointerGesture.currentGestureCoords[0].clear();
2916 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2917 mPointerGesture.tapX);
2918 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2919 mPointerGesture.tapY);
2920 mPointerGesture.currentGestureCoords[0]
2921 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2922
2923 tapped = true;
2924 } else {
2925#if DEBUG_GESTURES
2926 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2927 y - mPointerGesture.tapY);
2928#endif
2929 }
2930 } else {
2931#if DEBUG_GESTURES
2932 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2933 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2934 (when - mPointerGesture.tapDownTime) * 0.000001f);
2935 } else {
2936 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2937 }
2938#endif
2939 }
2940 }
2941
2942 mPointerVelocityControl.reset();
2943
2944 if (!tapped) {
2945#if DEBUG_GESTURES
2946 ALOGD("Gestures: NEUTRAL");
2947#endif
2948 mPointerGesture.activeGestureId = -1;
Michael Wright227c5542020-07-02 18:30:52 +01002949 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002950 mPointerGesture.currentGestureIdBits.clear();
2951 }
2952 } else if (currentFingerCount == 1) {
2953 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2954 // The pointer follows the active touch point.
2955 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2956 // When in TAP_DRAG, emit MOVE events at the pointer location.
2957 ALOG_ASSERT(activeTouchId >= 0);
2958
Michael Wright227c5542020-07-02 18:30:52 +01002959 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2960 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002961 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08002962 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002963 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2964 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wright227c5542020-07-02 18:30:52 +01002965 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002966 } else {
2967#if DEBUG_GESTURES
2968 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2969 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2970#endif
2971 }
2972 } else {
2973#if DEBUG_GESTURES
2974 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2975 (when - mPointerGesture.tapUpTime) * 0.000001f);
2976#endif
2977 }
Michael Wright227c5542020-07-02 18:30:52 +01002978 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2979 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002980 }
2981
2982 float deltaX = 0, deltaY = 0;
2983 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2984 const RawPointerData::Pointer& currentPointer =
2985 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2986 const RawPointerData::Pointer& lastPointer =
2987 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2988 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2989 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2990
2991 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2992 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2993
2994 // Move the pointer using a relative motion.
2995 // When using spots, the hover or drag will occur at the position of the anchor spot.
Prabir Pradhand7482e72021-03-09 13:54:55 -08002996 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002997 } else {
2998 mPointerVelocityControl.reset();
2999 }
3000
3001 bool down;
Michael Wright227c5542020-07-02 18:30:52 +01003002 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003003#if DEBUG_GESTURES
3004 ALOGD("Gestures: TAP_DRAG");
3005#endif
3006 down = true;
3007 } else {
3008#if DEBUG_GESTURES
3009 ALOGD("Gestures: HOVER");
3010#endif
Michael Wright227c5542020-07-02 18:30:52 +01003011 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003012 *outFinishPreviousGesture = true;
3013 }
3014 mPointerGesture.activeGestureId = 0;
3015 down = false;
3016 }
3017
Prabir Pradhand7482e72021-03-09 13:54:55 -08003018 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003019
3020 mPointerGesture.currentGestureIdBits.clear();
3021 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3022 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3023 mPointerGesture.currentGestureProperties[0].clear();
3024 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3025 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3026 mPointerGesture.currentGestureCoords[0].clear();
3027 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
3028 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3029 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3030 down ? 1.0f : 0.0f);
3031
3032 if (lastFingerCount == 0 && currentFingerCount != 0) {
3033 mPointerGesture.resetTap();
3034 mPointerGesture.tapDownTime = when;
3035 mPointerGesture.tapX = x;
3036 mPointerGesture.tapY = y;
3037 }
3038 } else {
3039 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
3040 // We need to provide feedback for each finger that goes down so we cannot wait
3041 // for the fingers to move before deciding what to do.
3042 //
3043 // The ambiguous case is deciding what to do when there are two fingers down but they
3044 // have not moved enough to determine whether they are part of a drag or part of a
3045 // freeform gesture, or just a press or long-press at the pointer location.
3046 //
3047 // When there are two fingers we start with the PRESS hypothesis and we generate a
3048 // down at the pointer location.
3049 //
3050 // When the two fingers move enough or when additional fingers are added, we make
3051 // a decision to transition into SWIPE or FREEFORM mode accordingly.
3052 ALOG_ASSERT(activeTouchId >= 0);
3053
3054 bool settled = when >=
3055 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wright227c5542020-07-02 18:30:52 +01003056 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
3057 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
3058 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003059 *outFinishPreviousGesture = true;
3060 } else if (!settled && currentFingerCount > lastFingerCount) {
3061 // Additional pointers have gone down but not yet settled.
3062 // Reset the gesture.
3063#if DEBUG_GESTURES
3064 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
3065 "settle time remaining %0.3fms",
3066 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3067 when) * 0.000001f);
3068#endif
3069 *outCancelPreviousGesture = true;
3070 } else {
3071 // Continue previous gesture.
3072 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3073 }
3074
3075 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wright227c5542020-07-02 18:30:52 +01003076 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003077 mPointerGesture.activeGestureId = 0;
3078 mPointerGesture.referenceIdBits.clear();
3079 mPointerVelocityControl.reset();
3080
3081 // Use the centroid and pointer location as the reference points for the gesture.
3082#if DEBUG_GESTURES
3083 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3084 "settle time remaining %0.3fms",
3085 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3086 when) * 0.000001f);
3087#endif
3088 mCurrentRawState.rawPointerData
3089 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3090 &mPointerGesture.referenceTouchY);
Prabir Pradhand7482e72021-03-09 13:54:55 -08003091 auto [x, y] = getMouseCursorPosition();
3092 mPointerGesture.referenceGestureX = x;
3093 mPointerGesture.referenceGestureY = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003094 }
3095
3096 // Clear the reference deltas for fingers not yet included in the reference calculation.
3097 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3098 ~mPointerGesture.referenceIdBits.value);
3099 !idBits.isEmpty();) {
3100 uint32_t id = idBits.clearFirstMarkedBit();
3101 mPointerGesture.referenceDeltas[id].dx = 0;
3102 mPointerGesture.referenceDeltas[id].dy = 0;
3103 }
3104 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3105
3106 // Add delta for all fingers and calculate a common movement delta.
3107 float commonDeltaX = 0, commonDeltaY = 0;
3108 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3109 mCurrentCookedState.fingerIdBits.value);
3110 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3111 bool first = (idBits == commonIdBits);
3112 uint32_t id = idBits.clearFirstMarkedBit();
3113 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3114 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3115 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3116 delta.dx += cpd.x - lpd.x;
3117 delta.dy += cpd.y - lpd.y;
3118
3119 if (first) {
3120 commonDeltaX = delta.dx;
3121 commonDeltaY = delta.dy;
3122 } else {
3123 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3124 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3125 }
3126 }
3127
3128 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wright227c5542020-07-02 18:30:52 +01003129 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003130 float dist[MAX_POINTER_ID + 1];
3131 int32_t distOverThreshold = 0;
3132 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3133 uint32_t id = idBits.clearFirstMarkedBit();
3134 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3135 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3136 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3137 distOverThreshold += 1;
3138 }
3139 }
3140
3141 // Only transition when at least two pointers have moved further than
3142 // the minimum distance threshold.
3143 if (distOverThreshold >= 2) {
3144 if (currentFingerCount > 2) {
3145 // There are more than two pointers, switch to FREEFORM.
3146#if DEBUG_GESTURES
3147 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3148 currentFingerCount);
3149#endif
3150 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003151 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003152 } else {
3153 // There are exactly two pointers.
3154 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3155 uint32_t id1 = idBits.clearFirstMarkedBit();
3156 uint32_t id2 = idBits.firstMarkedBit();
3157 const RawPointerData::Pointer& p1 =
3158 mCurrentRawState.rawPointerData.pointerForId(id1);
3159 const RawPointerData::Pointer& p2 =
3160 mCurrentRawState.rawPointerData.pointerForId(id2);
3161 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3162 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3163 // There are two pointers but they are too far apart for a SWIPE,
3164 // switch to FREEFORM.
3165#if DEBUG_GESTURES
3166 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3167 mutualDistance, mPointerGestureMaxSwipeWidth);
3168#endif
3169 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003170 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003171 } else {
3172 // There are two pointers. Wait for both pointers to start moving
3173 // before deciding whether this is a SWIPE or FREEFORM gesture.
3174 float dist1 = dist[id1];
3175 float dist2 = dist[id2];
3176 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3177 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3178 // Calculate the dot product of the displacement vectors.
3179 // When the vectors are oriented in approximately the same direction,
3180 // the angle betweeen them is near zero and the cosine of the angle
3181 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3182 // mag(v2).
3183 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3184 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3185 float dx1 = delta1.dx * mPointerXZoomScale;
3186 float dy1 = delta1.dy * mPointerYZoomScale;
3187 float dx2 = delta2.dx * mPointerXZoomScale;
3188 float dy2 = delta2.dy * mPointerYZoomScale;
3189 float dot = dx1 * dx2 + dy1 * dy2;
3190 float cosine = dot / (dist1 * dist2); // denominator always > 0
3191 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3192 // Pointers are moving in the same direction. Switch to SWIPE.
3193#if DEBUG_GESTURES
3194 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3195 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3196 "cosine %0.3f >= %0.3f",
3197 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3198 mConfig.pointerGestureMultitouchMinDistance, cosine,
3199 mConfig.pointerGestureSwipeTransitionAngleCosine);
3200#endif
Michael Wright227c5542020-07-02 18:30:52 +01003201 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003202 } else {
3203 // Pointers are moving in different directions. Switch to FREEFORM.
3204#if DEBUG_GESTURES
3205 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3206 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3207 "cosine %0.3f < %0.3f",
3208 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3209 mConfig.pointerGestureMultitouchMinDistance, cosine,
3210 mConfig.pointerGestureSwipeTransitionAngleCosine);
3211#endif
3212 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003213 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003214 }
3215 }
3216 }
3217 }
3218 }
Michael Wright227c5542020-07-02 18:30:52 +01003219 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003220 // Switch from SWIPE to FREEFORM if additional pointers go down.
3221 // Cancel previous gesture.
3222 if (currentFingerCount > 2) {
3223#if DEBUG_GESTURES
3224 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3225 currentFingerCount);
3226#endif
3227 *outCancelPreviousGesture = true;
Michael Wright227c5542020-07-02 18:30:52 +01003228 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003229 }
3230 }
3231
3232 // Move the reference points based on the overall group motion of the fingers
3233 // except in PRESS mode while waiting for a transition to occur.
Michael Wright227c5542020-07-02 18:30:52 +01003234 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003235 (commonDeltaX || commonDeltaY)) {
3236 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3237 uint32_t id = idBits.clearFirstMarkedBit();
3238 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3239 delta.dx = 0;
3240 delta.dy = 0;
3241 }
3242
3243 mPointerGesture.referenceTouchX += commonDeltaX;
3244 mPointerGesture.referenceTouchY += commonDeltaY;
3245
3246 commonDeltaX *= mPointerXMovementScale;
3247 commonDeltaY *= mPointerYMovementScale;
3248
3249 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3250 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3251
3252 mPointerGesture.referenceGestureX += commonDeltaX;
3253 mPointerGesture.referenceGestureY += commonDeltaY;
3254 }
3255
3256 // Report gestures.
Michael Wright227c5542020-07-02 18:30:52 +01003257 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3258 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003259 // PRESS or SWIPE mode.
3260#if DEBUG_GESTURES
3261 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3262 "activeGestureId=%d, currentTouchPointerCount=%d",
3263 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3264#endif
3265 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3266
3267 mPointerGesture.currentGestureIdBits.clear();
3268 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3269 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3270 mPointerGesture.currentGestureProperties[0].clear();
3271 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3272 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3273 mPointerGesture.currentGestureCoords[0].clear();
3274 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3275 mPointerGesture.referenceGestureX);
3276 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3277 mPointerGesture.referenceGestureY);
3278 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wright227c5542020-07-02 18:30:52 +01003279 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003280 // FREEFORM mode.
3281#if DEBUG_GESTURES
3282 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3283 "activeGestureId=%d, currentTouchPointerCount=%d",
3284 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3285#endif
3286 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3287
3288 mPointerGesture.currentGestureIdBits.clear();
3289
3290 BitSet32 mappedTouchIdBits;
3291 BitSet32 usedGestureIdBits;
Michael Wright227c5542020-07-02 18:30:52 +01003292 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003293 // Initially, assign the active gesture id to the active touch point
3294 // if there is one. No other touch id bits are mapped yet.
3295 if (!*outCancelPreviousGesture) {
3296 mappedTouchIdBits.markBit(activeTouchId);
3297 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3298 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3299 mPointerGesture.activeGestureId;
3300 } else {
3301 mPointerGesture.activeGestureId = -1;
3302 }
3303 } else {
3304 // Otherwise, assume we mapped all touches from the previous frame.
3305 // Reuse all mappings that are still applicable.
3306 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3307 mCurrentCookedState.fingerIdBits.value;
3308 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3309
3310 // Check whether we need to choose a new active gesture id because the
3311 // current went went up.
3312 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3313 ~mCurrentCookedState.fingerIdBits.value);
3314 !upTouchIdBits.isEmpty();) {
3315 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3316 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3317 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3318 mPointerGesture.activeGestureId = -1;
3319 break;
3320 }
3321 }
3322 }
3323
3324#if DEBUG_GESTURES
3325 ALOGD("Gestures: FREEFORM follow up "
3326 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3327 "activeGestureId=%d",
3328 mappedTouchIdBits.value, usedGestureIdBits.value,
3329 mPointerGesture.activeGestureId);
3330#endif
3331
3332 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3333 for (uint32_t i = 0; i < currentFingerCount; i++) {
3334 uint32_t touchId = idBits.clearFirstMarkedBit();
3335 uint32_t gestureId;
3336 if (!mappedTouchIdBits.hasBit(touchId)) {
3337 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3338 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3339#if DEBUG_GESTURES
3340 ALOGD("Gestures: FREEFORM "
3341 "new mapping for touch id %d -> gesture id %d",
3342 touchId, gestureId);
3343#endif
3344 } else {
3345 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3346#if DEBUG_GESTURES
3347 ALOGD("Gestures: FREEFORM "
3348 "existing mapping for touch id %d -> gesture id %d",
3349 touchId, gestureId);
3350#endif
3351 }
3352 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3353 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3354
3355 const RawPointerData::Pointer& pointer =
3356 mCurrentRawState.rawPointerData.pointerForId(touchId);
3357 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3358 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3359 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3360
3361 mPointerGesture.currentGestureProperties[i].clear();
3362 mPointerGesture.currentGestureProperties[i].id = gestureId;
3363 mPointerGesture.currentGestureProperties[i].toolType =
3364 AMOTION_EVENT_TOOL_TYPE_FINGER;
3365 mPointerGesture.currentGestureCoords[i].clear();
3366 mPointerGesture.currentGestureCoords[i]
3367 .setAxisValue(AMOTION_EVENT_AXIS_X,
3368 mPointerGesture.referenceGestureX + deltaX);
3369 mPointerGesture.currentGestureCoords[i]
3370 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3371 mPointerGesture.referenceGestureY + deltaY);
3372 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3373 1.0f);
3374 }
3375
3376 if (mPointerGesture.activeGestureId < 0) {
3377 mPointerGesture.activeGestureId =
3378 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3379#if DEBUG_GESTURES
3380 ALOGD("Gestures: FREEFORM new "
3381 "activeGestureId=%d",
3382 mPointerGesture.activeGestureId);
3383#endif
3384 }
3385 }
3386 }
3387
3388 mPointerController->setButtonState(mCurrentRawState.buttonState);
3389
3390#if DEBUG_GESTURES
3391 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3392 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3393 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3394 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3395 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3396 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3397 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3398 uint32_t id = idBits.clearFirstMarkedBit();
3399 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3400 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3401 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3402 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3403 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3404 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3405 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3406 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3407 }
3408 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3409 uint32_t id = idBits.clearFirstMarkedBit();
3410 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3411 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3412 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3413 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3414 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3415 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3416 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3417 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3418 }
3419#endif
3420 return true;
3421}
3422
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003423void TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003424 mPointerSimple.currentCoords.clear();
3425 mPointerSimple.currentProperties.clear();
3426
3427 bool down, hovering;
3428 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3429 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3430 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
Prabir Pradhand7482e72021-03-09 13:54:55 -08003431 setMouseCursorPosition(mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(),
3432 mCurrentCookedState.cookedPointerData.pointerCoords[index].getY());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003433
3434 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3435 down = !hovering;
3436
Prabir Pradhand7482e72021-03-09 13:54:55 -08003437 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003438 mPointerSimple.currentCoords.copyFrom(
3439 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3440 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3441 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3442 mPointerSimple.currentProperties.id = 0;
3443 mPointerSimple.currentProperties.toolType =
3444 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3445 } else {
3446 down = false;
3447 hovering = false;
3448 }
3449
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003450 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003451}
3452
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003453void TouchInputMapper::abortPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3454 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003455}
3456
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003457void TouchInputMapper::dispatchPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003458 mPointerSimple.currentCoords.clear();
3459 mPointerSimple.currentProperties.clear();
3460
3461 bool down, hovering;
3462 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3463 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3464 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3465 float deltaX = 0, deltaY = 0;
3466 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3467 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3468 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3469 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3470 mPointerXMovementScale;
3471 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3472 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3473 mPointerYMovementScale;
3474
3475 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3476 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3477
Prabir Pradhand7482e72021-03-09 13:54:55 -08003478 moveMouseCursor(deltaX, deltaY);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003479 } else {
3480 mPointerVelocityControl.reset();
3481 }
3482
3483 down = isPointerDown(mCurrentRawState.buttonState);
3484 hovering = !down;
3485
Prabir Pradhand7482e72021-03-09 13:54:55 -08003486 auto [x, y] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003487 mPointerSimple.currentCoords.copyFrom(
3488 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3489 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3490 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3491 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3492 hovering ? 0.0f : 1.0f);
3493 mPointerSimple.currentProperties.id = 0;
3494 mPointerSimple.currentProperties.toolType =
3495 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3496 } else {
3497 mPointerVelocityControl.reset();
3498
3499 down = false;
3500 hovering = false;
3501 }
3502
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003503 dispatchPointerSimple(when, readTime, policyFlags, down, hovering);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003504}
3505
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003506void TouchInputMapper::abortPointerMouse(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
3507 abortPointerSimple(when, readTime, policyFlags);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003508
3509 mPointerVelocityControl.reset();
3510}
3511
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003512void TouchInputMapper::dispatchPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3513 bool down, bool hovering) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003514 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003515
3516 if (down || hovering) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003517 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003518 mPointerController->clearSpots();
3519 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wrightca5bede2020-07-02 00:00:29 +01003520 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003521 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wrightca5bede2020-07-02 00:00:29 +01003522 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003523 }
Garfield Tan9514d782020-11-10 16:37:23 -08003524 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003525
Prabir Pradhand7482e72021-03-09 13:54:55 -08003526 auto [xCursorPosition, yCursorPosition] = getMouseCursorPosition();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003527
3528 if (mPointerSimple.down && !down) {
3529 mPointerSimple.down = false;
3530
3531 // Send up.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003532 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3533 displayId, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003534 mLastRawState.buttonState, MotionClassification::NONE,
3535 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3536 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3537 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3538 /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003539 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003540 }
3541
3542 if (mPointerSimple.hovering && !hovering) {
3543 mPointerSimple.hovering = false;
3544
3545 // Send hover exit.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003546 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3547 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0,
3548 metaState, mLastRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003549 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3550 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3551 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3552 /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003553 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003554 }
3555
3556 if (down) {
3557 if (!mPointerSimple.down) {
3558 mPointerSimple.down = true;
3559 mPointerSimple.downTime = when;
3560
3561 // Send down.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003562 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003563 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3564 metaState, mCurrentRawState.buttonState,
3565 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3566 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3567 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3568 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003569 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003570 }
3571
3572 // Send move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003573 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3574 displayId, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003575 mCurrentRawState.buttonState, MotionClassification::NONE,
3576 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3577 &mPointerSimple.currentCoords, mOrientedXPrecision,
3578 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3579 mPointerSimple.downTime, /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003580 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003581 }
3582
3583 if (hovering) {
3584 if (!mPointerSimple.hovering) {
3585 mPointerSimple.hovering = true;
3586
3587 // Send hover enter.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003588 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003589 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3590 metaState, mCurrentRawState.buttonState,
3591 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3592 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3593 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3594 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003595 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003596 }
3597
3598 // Send hover move.
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003599 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3600 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
3601 metaState, mCurrentRawState.buttonState, MotionClassification::NONE,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003602 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3603 &mPointerSimple.currentCoords, mOrientedXPrecision,
3604 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3605 mPointerSimple.downTime, /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003606 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003607 }
3608
3609 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3610 float vscroll = mCurrentRawState.rawVScroll;
3611 float hscroll = mCurrentRawState.rawHScroll;
3612 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3613 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3614
3615 // Send scroll.
3616 PointerCoords pointerCoords;
3617 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3618 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3619 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3620
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003621 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
3622 displayId, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003623 mCurrentRawState.buttonState, MotionClassification::NONE,
3624 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3625 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3626 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3627 /* videoFrames */ {});
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003628 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003629 }
3630
3631 // Save state.
3632 if (down || hovering) {
3633 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3634 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3635 } else {
3636 mPointerSimple.reset();
3637 }
3638}
3639
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003640void TouchInputMapper::abortPointerSimple(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003641 mPointerSimple.currentCoords.clear();
3642 mPointerSimple.currentProperties.clear();
3643
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003644 dispatchPointerSimple(when, readTime, policyFlags, false, false);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003645}
3646
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003647void TouchInputMapper::dispatchMotion(nsecs_t when, nsecs_t readTime, uint32_t policyFlags,
3648 uint32_t source, int32_t action, int32_t actionButton,
3649 int32_t flags, int32_t metaState, int32_t buttonState,
3650 int32_t edgeFlags, const PointerProperties* properties,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003651 const PointerCoords* coords, const uint32_t* idToIndex,
3652 BitSet32 idBits, int32_t changedId, float xPrecision,
3653 float yPrecision, nsecs_t downTime) {
3654 PointerCoords pointerCoords[MAX_POINTERS];
3655 PointerProperties pointerProperties[MAX_POINTERS];
3656 uint32_t pointerCount = 0;
3657 while (!idBits.isEmpty()) {
3658 uint32_t id = idBits.clearFirstMarkedBit();
3659 uint32_t index = idToIndex[id];
3660 pointerProperties[pointerCount].copyFrom(properties[index]);
3661 pointerCoords[pointerCount].copyFrom(coords[index]);
3662
3663 if (changedId >= 0 && id == uint32_t(changedId)) {
3664 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3665 }
3666
3667 pointerCount += 1;
3668 }
3669
3670 ALOG_ASSERT(pointerCount != 0);
3671
3672 if (changedId >= 0 && pointerCount == 1) {
3673 // Replace initial down and final up action.
3674 // We can compare the action without masking off the changed pointer index
3675 // because we know the index is 0.
3676 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3677 action = AMOTION_EVENT_ACTION_DOWN;
3678 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhungcc7f9802020-04-30 17:55:40 +08003679 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3680 action = AMOTION_EVENT_ACTION_CANCEL;
3681 } else {
3682 action = AMOTION_EVENT_ACTION_UP;
3683 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003684 } else {
3685 // Can't happen.
3686 ALOG_ASSERT(false);
3687 }
3688 }
3689 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3690 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wright227c5542020-07-02 18:30:52 +01003691 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhand7482e72021-03-09 13:54:55 -08003692 auto [x, y] = getMouseCursorPosition();
3693 xCursorPosition = x;
3694 yCursorPosition = y;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003695 }
3696 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3697 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003698 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003699 std::for_each(frames.begin(), frames.end(),
3700 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003701 NotifyMotionArgs args(getContext()->getNextId(), when, readTime, deviceId, source, displayId,
3702 policyFlags, action, actionButton, flags, metaState, buttonState,
Siarhei Vishniakouf2f073b2021-02-09 21:59:56 +00003703 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3704 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3705 downTime, std::move(frames));
Siarhei Vishniakou18050092021-09-01 13:32:49 -07003706 getListener().notifyMotion(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003707}
3708
3709bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3710 const PointerCoords* inCoords,
3711 const uint32_t* inIdToIndex,
3712 PointerProperties* outProperties,
3713 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3714 BitSet32 idBits) const {
3715 bool changed = false;
3716 while (!idBits.isEmpty()) {
3717 uint32_t id = idBits.clearFirstMarkedBit();
3718 uint32_t inIndex = inIdToIndex[id];
3719 uint32_t outIndex = outIdToIndex[id];
3720
3721 const PointerProperties& curInProperties = inProperties[inIndex];
3722 const PointerCoords& curInCoords = inCoords[inIndex];
3723 PointerProperties& curOutProperties = outProperties[outIndex];
3724 PointerCoords& curOutCoords = outCoords[outIndex];
3725
3726 if (curInProperties != curOutProperties) {
3727 curOutProperties.copyFrom(curInProperties);
3728 changed = true;
3729 }
3730
3731 if (curInCoords != curOutCoords) {
3732 curOutCoords.copyFrom(curInCoords);
3733 changed = true;
3734 }
3735 }
3736 return changed;
3737}
3738
Siarhei Vishniakou58ba3d12021-02-11 01:31:07 +00003739void TouchInputMapper::cancelTouch(nsecs_t when, nsecs_t readTime) {
3740 abortPointerUsage(when, readTime, 0 /*policyFlags*/);
3741 abortTouches(when, readTime, 0 /* policyFlags*/);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003742}
3743
Arthur Hung4197f6b2020-03-16 15:39:59 +08003744// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003745void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003746 // Scale to surface coordinate.
3747 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3748 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3749
arthurhunga36b28e2020-12-29 20:28:15 +08003750 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3751 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3752
Arthur Hung4197f6b2020-03-16 15:39:59 +08003753 // Rotate to surface coordinate.
3754 // 0 - no swap and reverse.
3755 // 90 - swap x/y and reverse y.
3756 // 180 - reverse x, y.
3757 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003758 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003759 case DISPLAY_ORIENTATION_0:
3760 x = xScaled + mXTranslate;
3761 y = yScaled + mYTranslate;
3762 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003763 case DISPLAY_ORIENTATION_90:
arthurhunga36b28e2020-12-29 20:28:15 +08003764 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003765 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003766 break;
3767 case DISPLAY_ORIENTATION_180:
arthurhunga36b28e2020-12-29 20:28:15 +08003768 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3769 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003770 break;
3771 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003772 y = xScaled + mXTranslate;
arthurhunga36b28e2020-12-29 20:28:15 +08003773 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003774 break;
3775 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003776 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003777 }
3778}
3779
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003780bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003781 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3782 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3783
Prabir Pradhan5632d622021-09-06 07:57:20 -07003784 if (isPerWindowInputRotationEnabled()) {
3785 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
3786 xScaled >= mPhysicalLeft && xScaled <= (mPhysicalLeft + mPhysicalWidth) &&
3787 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
3788 yScaled >= mPhysicalTop && yScaled <= (mPhysicalTop + mPhysicalHeight);
3789 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003790 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003791 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003792 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003793 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003794}
3795
3796const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3797 for (const VirtualKey& virtualKey : mVirtualKeys) {
3798#if DEBUG_VIRTUAL_KEYS
3799 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3800 "left=%d, top=%d, right=%d, bottom=%d",
3801 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3802 virtualKey.hitRight, virtualKey.hitBottom);
3803#endif
3804
3805 if (virtualKey.isHit(x, y)) {
3806 return &virtualKey;
3807 }
3808 }
3809
3810 return nullptr;
3811}
3812
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003813void TouchInputMapper::assignPointerIds(const RawState& last, RawState& current) {
3814 uint32_t currentPointerCount = current.rawPointerData.pointerCount;
3815 uint32_t lastPointerCount = last.rawPointerData.pointerCount;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003816
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003817 current.rawPointerData.clearIdBits();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003818
3819 if (currentPointerCount == 0) {
3820 // No pointers to assign.
3821 return;
3822 }
3823
3824 if (lastPointerCount == 0) {
3825 // All pointers are new.
3826 for (uint32_t i = 0; i < currentPointerCount; i++) {
3827 uint32_t id = i;
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003828 current.rawPointerData.pointers[i].id = id;
3829 current.rawPointerData.idToIndex[id] = i;
3830 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(i));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003831 }
3832 return;
3833 }
3834
3835 if (currentPointerCount == 1 && lastPointerCount == 1 &&
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003836 current.rawPointerData.pointers[0].toolType == last.rawPointerData.pointers[0].toolType) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003837 // Only one pointer and no change in count so it must have the same id as before.
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003838 uint32_t id = last.rawPointerData.pointers[0].id;
3839 current.rawPointerData.pointers[0].id = id;
3840 current.rawPointerData.idToIndex[id] = 0;
3841 current.rawPointerData.markIdBit(id, current.rawPointerData.isHovering(0));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003842 return;
3843 }
3844
3845 // General case.
3846 // We build a heap of squared euclidean distances between current and last pointers
3847 // associated with the current and last pointer indices. Then, we find the best
3848 // match (by distance) for each current pointer.
3849 // The pointers must have the same tool type but it is possible for them to
3850 // transition from hovering to touching or vice-versa while retaining the same id.
3851 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3852
3853 uint32_t heapSize = 0;
3854 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3855 currentPointerIndex++) {
3856 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3857 lastPointerIndex++) {
3858 const RawPointerData::Pointer& currentPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003859 current.rawPointerData.pointers[currentPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003860 const RawPointerData::Pointer& lastPointer =
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003861 last.rawPointerData.pointers[lastPointerIndex];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003862 if (currentPointer.toolType == lastPointer.toolType) {
3863 int64_t deltaX = currentPointer.x - lastPointer.x;
3864 int64_t deltaY = currentPointer.y - lastPointer.y;
3865
3866 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3867
3868 // Insert new element into the heap (sift up).
3869 heap[heapSize].currentPointerIndex = currentPointerIndex;
3870 heap[heapSize].lastPointerIndex = lastPointerIndex;
3871 heap[heapSize].distance = distance;
3872 heapSize += 1;
3873 }
3874 }
3875 }
3876
3877 // Heapify
3878 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3879 startIndex -= 1;
3880 for (uint32_t parentIndex = startIndex;;) {
3881 uint32_t childIndex = parentIndex * 2 + 1;
3882 if (childIndex >= heapSize) {
3883 break;
3884 }
3885
3886 if (childIndex + 1 < heapSize &&
3887 heap[childIndex + 1].distance < heap[childIndex].distance) {
3888 childIndex += 1;
3889 }
3890
3891 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3892 break;
3893 }
3894
3895 swap(heap[parentIndex], heap[childIndex]);
3896 parentIndex = childIndex;
3897 }
3898 }
3899
3900#if DEBUG_POINTER_ASSIGNMENT
3901 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3902 for (size_t i = 0; i < heapSize; i++) {
3903 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3904 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3905 }
3906#endif
3907
3908 // Pull matches out by increasing order of distance.
3909 // To avoid reassigning pointers that have already been matched, the loop keeps track
3910 // of which last and current pointers have been matched using the matchedXXXBits variables.
3911 // It also tracks the used pointer id bits.
3912 BitSet32 matchedLastBits(0);
3913 BitSet32 matchedCurrentBits(0);
3914 BitSet32 usedIdBits(0);
3915 bool first = true;
3916 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3917 while (heapSize > 0) {
3918 if (first) {
3919 // The first time through the loop, we just consume the root element of
3920 // the heap (the one with smallest distance).
3921 first = false;
3922 } else {
3923 // Previous iterations consumed the root element of the heap.
3924 // Pop root element off of the heap (sift down).
3925 heap[0] = heap[heapSize];
3926 for (uint32_t parentIndex = 0;;) {
3927 uint32_t childIndex = parentIndex * 2 + 1;
3928 if (childIndex >= heapSize) {
3929 break;
3930 }
3931
3932 if (childIndex + 1 < heapSize &&
3933 heap[childIndex + 1].distance < heap[childIndex].distance) {
3934 childIndex += 1;
3935 }
3936
3937 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3938 break;
3939 }
3940
3941 swap(heap[parentIndex], heap[childIndex]);
3942 parentIndex = childIndex;
3943 }
3944
3945#if DEBUG_POINTER_ASSIGNMENT
3946 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
Philip Quinn35c872f2020-08-03 02:32:51 -07003947 for (size_t j = 0; j < heapSize; j++) {
3948 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, j,
3949 heap[j].currentPointerIndex, heap[j].lastPointerIndex, heap[j].distance);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003950 }
3951#endif
3952 }
3953
3954 heapSize -= 1;
3955
3956 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3957 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3958
3959 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3960 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3961
3962 matchedCurrentBits.markBit(currentPointerIndex);
3963 matchedLastBits.markBit(lastPointerIndex);
3964
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003965 uint32_t id = last.rawPointerData.pointers[lastPointerIndex].id;
3966 current.rawPointerData.pointers[currentPointerIndex].id = id;
3967 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3968 current.rawPointerData.markIdBit(id,
3969 current.rawPointerData.isHovering(
3970 currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003971 usedIdBits.markBit(id);
3972
3973#if DEBUG_POINTER_ASSIGNMENT
3974 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3975 ", distance=%" PRIu64,
3976 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3977#endif
3978 break;
3979 }
3980 }
3981
3982 // Assign fresh ids to pointers that were not matched in the process.
3983 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3984 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3985 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3986
Siarhei Vishniakou57479982021-03-03 01:32:21 +00003987 current.rawPointerData.pointers[currentPointerIndex].id = id;
3988 current.rawPointerData.idToIndex[id] = currentPointerIndex;
3989 current.rawPointerData.markIdBit(id,
3990 current.rawPointerData.isHovering(currentPointerIndex));
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003991
3992#if DEBUG_POINTER_ASSIGNMENT
3993 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3994#endif
3995 }
3996}
3997
3998int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3999 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
4000 return AKEY_STATE_VIRTUAL;
4001 }
4002
4003 for (const VirtualKey& virtualKey : mVirtualKeys) {
4004 if (virtualKey.keyCode == keyCode) {
4005 return AKEY_STATE_UP;
4006 }
4007 }
4008
4009 return AKEY_STATE_UNKNOWN;
4010}
4011
4012int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
4013 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
4014 return AKEY_STATE_VIRTUAL;
4015 }
4016
4017 for (const VirtualKey& virtualKey : mVirtualKeys) {
4018 if (virtualKey.scanCode == scanCode) {
4019 return AKEY_STATE_UP;
4020 }
4021 }
4022
4023 return AKEY_STATE_UNKNOWN;
4024}
4025
4026bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
4027 const int32_t* keyCodes, uint8_t* outFlags) {
4028 for (const VirtualKey& virtualKey : mVirtualKeys) {
4029 for (size_t i = 0; i < numCodes; i++) {
4030 if (virtualKey.keyCode == keyCodes[i]) {
4031 outFlags[i] = 1;
4032 }
4033 }
4034 }
4035
4036 return true;
4037}
4038
4039std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
4040 if (mParameters.hasAssociatedDisplay) {
Michael Wright227c5542020-07-02 18:30:52 +01004041 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004042 return std::make_optional(mPointerController->getDisplayId());
4043 } else {
4044 return std::make_optional(mViewport.displayId);
4045 }
4046 }
4047 return std::nullopt;
4048}
4049
Prabir Pradhand7482e72021-03-09 13:54:55 -08004050void TouchInputMapper::moveMouseCursor(float dx, float dy) const {
4051 if (isPerWindowInputRotationEnabled()) {
4052 // Convert from InputReader's un-rotated coordinate space to PointerController's coordinate
4053 // space that is oriented with the viewport.
4054 rotateDelta(mViewport.orientation, &dx, &dy);
4055 }
4056
4057 mPointerController->move(dx, dy);
4058}
4059
4060std::pair<float, float> TouchInputMapper::getMouseCursorPosition() const {
4061 float x = 0;
4062 float y = 0;
4063 mPointerController->getPosition(&x, &y);
4064
4065 if (!isPerWindowInputRotationEnabled()) return {x, y};
4066 if (!mViewport.isValid()) return {x, y};
4067
4068 // Convert from PointerController's rotated coordinate space that is oriented with the viewport
4069 // to InputReader's un-rotated coordinate space.
4070 const int32_t orientation = getInverseRotation(mViewport.orientation);
4071 rotatePoint(orientation, x, y, mViewport.deviceWidth, mViewport.deviceHeight);
4072 return {x, y};
4073}
4074
4075void TouchInputMapper::setMouseCursorPosition(float x, float y) const {
4076 if (isPerWindowInputRotationEnabled() && mViewport.isValid()) {
4077 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4078 // coordinate space that is oriented with the viewport.
4079 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4080 }
4081
4082 mPointerController->setPosition(x, y);
4083}
4084
4085void TouchInputMapper::setTouchSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex,
4086 BitSet32 spotIdBits, int32_t displayId) {
4087 std::array<PointerCoords, MAX_POINTERS> outSpotCoords{};
4088
4089 for (BitSet32 idBits(spotIdBits); !idBits.isEmpty();) {
4090 const uint32_t index = spotIdToIndex[idBits.clearFirstMarkedBit()];
4091 float x = spotCoords[index].getX();
4092 float y = spotCoords[index].getY();
4093 float pressure = spotCoords[index].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
4094
4095 if (isPerWindowInputRotationEnabled()) {
4096 // Convert from InputReader's un-rotated coordinate space to PointerController's rotated
4097 // coordinate space.
4098 rotatePoint(mViewport.orientation, x, y, mRawSurfaceWidth, mRawSurfaceHeight);
4099 }
4100
4101 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_X, x);
4102 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
4103 outSpotCoords[index].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
4104 }
4105
4106 mPointerController->setSpots(outSpotCoords.data(), spotIdToIndex, spotIdBits, displayId);
4107}
4108
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07004109} // namespace android