blob: bfdc02cef6dbbab9f44d752211fb1d537708cda4 [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 Wrightaff169e2020-07-02 18:30:52 +010017// clang-format off
Prabir Pradhan9244aea2020-02-05 20:31:40 -080018#include "../Macros.h"
Michael Wrightaff169e2020-07-02 18:30:52 +010019// clang-format on
Prabir Pradhanbaa5c822019-08-30 15:27:05 -070020
21#include "TouchInputMapper.h"
22
23#include "CursorButtonAccumulator.h"
24#include "CursorScrollAccumulator.h"
25#include "TouchButtonAccumulator.h"
26#include "TouchCursorInputMapperCommon.h"
27
28namespace android {
29
30// --- Constants ---
31
32// Maximum amount of latency to add to touch events while waiting for data from an
33// external stylus.
34static constexpr nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72);
35
36// Maximum amount of time to wait on touch data before pushing out new pressure data.
37static constexpr nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20);
38
39// Artificial latency on synthetic events created from stylus data without corresponding touch
40// data.
41static constexpr nsecs_t STYLUS_DATA_LATENCY = ms2ns(10);
42
43// --- Static Definitions ---
44
45template <typename T>
46inline static void swap(T& a, T& b) {
47 T temp = a;
48 a = b;
49 b = temp;
50}
51
52static float calculateCommonVector(float a, float b) {
53 if (a > 0 && b > 0) {
54 return a < b ? a : b;
55 } else if (a < 0 && b < 0) {
56 return a > b ? a : b;
57 } else {
58 return 0;
59 }
60}
61
62inline static float distance(float x1, float y1, float x2, float y2) {
63 return hypotf(x1 - x2, y1 - y2);
64}
65
66inline static int32_t signExtendNybble(int32_t value) {
67 return value >= 8 ? value - 16 : value;
68}
69
70// --- RawPointerAxes ---
71
72RawPointerAxes::RawPointerAxes() {
73 clear();
74}
75
76void RawPointerAxes::clear() {
77 x.clear();
78 y.clear();
79 pressure.clear();
80 touchMajor.clear();
81 touchMinor.clear();
82 toolMajor.clear();
83 toolMinor.clear();
84 orientation.clear();
85 distance.clear();
86 tiltX.clear();
87 tiltY.clear();
88 trackingId.clear();
89 slot.clear();
90}
91
92// --- RawPointerData ---
93
94RawPointerData::RawPointerData() {
95 clear();
96}
97
98void RawPointerData::clear() {
99 pointerCount = 0;
100 clearIdBits();
101}
102
103void RawPointerData::copyFrom(const RawPointerData& other) {
104 pointerCount = other.pointerCount;
105 hoveringIdBits = other.hoveringIdBits;
106 touchingIdBits = other.touchingIdBits;
arthurhung65600042020-04-30 17:55:40 +0800107 canceledIdBits = other.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700108
109 for (uint32_t i = 0; i < pointerCount; i++) {
110 pointers[i] = other.pointers[i];
111
112 int id = pointers[i].id;
113 idToIndex[id] = other.idToIndex[id];
114 }
115}
116
117void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const {
118 float x = 0, y = 0;
119 uint32_t count = touchingIdBits.count();
120 if (count) {
121 for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty();) {
122 uint32_t id = idBits.clearFirstMarkedBit();
123 const Pointer& pointer = pointerForId(id);
124 x += pointer.x;
125 y += pointer.y;
126 }
127 x /= count;
128 y /= count;
129 }
130 *outX = x;
131 *outY = y;
132}
133
134// --- CookedPointerData ---
135
136CookedPointerData::CookedPointerData() {
137 clear();
138}
139
140void CookedPointerData::clear() {
141 pointerCount = 0;
142 hoveringIdBits.clear();
143 touchingIdBits.clear();
arthurhung65600042020-04-30 17:55:40 +0800144 canceledIdBits.clear();
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +0000145 validIdBits.clear();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700146}
147
148void CookedPointerData::copyFrom(const CookedPointerData& other) {
149 pointerCount = other.pointerCount;
150 hoveringIdBits = other.hoveringIdBits;
151 touchingIdBits = other.touchingIdBits;
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +0000152 validIdBits = other.validIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700153
154 for (uint32_t i = 0; i < pointerCount; i++) {
155 pointerProperties[i].copyFrom(other.pointerProperties[i]);
156 pointerCoords[i].copyFrom(other.pointerCoords[i]);
157
158 int id = pointerProperties[i].id;
159 idToIndex[id] = other.idToIndex[id];
160 }
161}
162
163// --- TouchInputMapper ---
164
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800165TouchInputMapper::TouchInputMapper(InputDeviceContext& deviceContext)
166 : InputMapper(deviceContext),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700167 mSource(0),
Michael Wrightaff169e2020-07-02 18:30:52 +0100168 mDeviceMode(DeviceMode::DISABLED),
Arthur Hung4197f6b2020-03-16 15:39:59 +0800169 mRawSurfaceWidth(-1),
170 mRawSurfaceHeight(-1),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700171 mSurfaceLeft(0),
172 mSurfaceTop(0),
173 mPhysicalWidth(-1),
174 mPhysicalHeight(-1),
175 mPhysicalLeft(0),
176 mPhysicalTop(0),
177 mSurfaceOrientation(DISPLAY_ORIENTATION_0) {}
178
179TouchInputMapper::~TouchInputMapper() {}
180
181uint32_t TouchInputMapper::getSources() {
182 return mSource;
183}
184
185void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) {
186 InputMapper::populateDeviceInfo(info);
187
Michael Wrightaff169e2020-07-02 18:30:52 +0100188 if (mDeviceMode != DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700189 info->addMotionRange(mOrientedRanges.x);
190 info->addMotionRange(mOrientedRanges.y);
191 info->addMotionRange(mOrientedRanges.pressure);
192
Chris Ye1fb45302020-09-02 22:41:50 -0700193 if (mDeviceMode == DeviceMode::UNSCALED && mSource == AINPUT_SOURCE_TOUCHPAD) {
Chris Ye4b2268c2020-09-15 17:17:34 -0700194 // Populate RELATIVE_X and RELATIVE_Y motion ranges for touchpad capture mode.
195 //
196 // RELATIVE_X and RELATIVE_Y motion ranges should be the largest possible relative
197 // motion, i.e. the hardware dimensions, as the finger could move completely across the
198 // touchpad in one sample cycle.
Chris Ye1fb45302020-09-02 22:41:50 -0700199 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
200 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
201 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_X, mSource, -x.max, x.max, x.flat,
202 x.fuzz, x.resolution);
203 info->addMotionRange(AMOTION_EVENT_AXIS_RELATIVE_Y, mSource, -y.max, y.max, y.flat,
204 y.fuzz, y.resolution);
205 }
206
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700207 if (mOrientedRanges.haveSize) {
208 info->addMotionRange(mOrientedRanges.size);
209 }
210
211 if (mOrientedRanges.haveTouchSize) {
212 info->addMotionRange(mOrientedRanges.touchMajor);
213 info->addMotionRange(mOrientedRanges.touchMinor);
214 }
215
216 if (mOrientedRanges.haveToolSize) {
217 info->addMotionRange(mOrientedRanges.toolMajor);
218 info->addMotionRange(mOrientedRanges.toolMinor);
219 }
220
221 if (mOrientedRanges.haveOrientation) {
222 info->addMotionRange(mOrientedRanges.orientation);
223 }
224
225 if (mOrientedRanges.haveDistance) {
226 info->addMotionRange(mOrientedRanges.distance);
227 }
228
229 if (mOrientedRanges.haveTilt) {
230 info->addMotionRange(mOrientedRanges.tilt);
231 }
232
233 if (mCursorScrollAccumulator.haveRelativeVWheel()) {
234 info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
235 0.0f);
236 }
237 if (mCursorScrollAccumulator.haveRelativeHWheel()) {
238 info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f,
239 0.0f);
240 }
Michael Wrightaff169e2020-07-02 18:30:52 +0100241 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700242 const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
243 const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
244 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat,
245 x.fuzz, x.resolution);
246 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat,
247 y.fuzz, y.resolution);
248 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat,
249 x.fuzz, x.resolution);
250 info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat,
251 y.fuzz, y.resolution);
252 }
253 info->setButtonUnderPad(mParameters.hasButtonUnderPad);
254 }
255}
256
257void TouchInputMapper::dump(std::string& dump) {
258 dump += StringPrintf(INDENT2 "Touch Input Mapper (mode - %s):\n", modeToString(mDeviceMode));
259 dumpParameters(dump);
260 dumpVirtualKeys(dump);
261 dumpRawPointerAxes(dump);
262 dumpCalibration(dump);
263 dumpAffineTransformation(dump);
264 dumpSurface(dump);
265
266 dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
267 dump += StringPrintf(INDENT4 "XTranslate: %0.3f\n", mXTranslate);
268 dump += StringPrintf(INDENT4 "YTranslate: %0.3f\n", mYTranslate);
269 dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
270 dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
271 dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
272 dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
273 dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
274 dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
275 dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
276 dump += StringPrintf(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale);
277 dump += StringPrintf(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale);
278 dump += StringPrintf(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt));
279 dump += StringPrintf(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter);
280 dump += StringPrintf(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale);
281 dump += StringPrintf(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter);
282 dump += StringPrintf(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale);
283
284 dump += StringPrintf(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState);
285 dump += StringPrintf(INDENT3 "Last Raw Touch: pointerCount=%d\n",
286 mLastRawState.rawPointerData.pointerCount);
287 for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) {
288 const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i];
289 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, "
290 "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, "
291 "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, "
292 "toolType=%d, isHovering=%s\n",
293 i, pointer.id, pointer.x, pointer.y, pointer.pressure,
294 pointer.touchMajor, pointer.touchMinor, pointer.toolMajor,
295 pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY,
296 pointer.distance, pointer.toolType, toString(pointer.isHovering));
297 }
298
299 dump += StringPrintf(INDENT3 "Last Cooked Button State: 0x%08x\n",
300 mLastCookedState.buttonState);
301 dump += StringPrintf(INDENT3 "Last Cooked Touch: pointerCount=%d\n",
302 mLastCookedState.cookedPointerData.pointerCount);
303 for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) {
304 const PointerProperties& pointerProperties =
305 mLastCookedState.cookedPointerData.pointerProperties[i];
306 const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i];
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +0000307 dump += StringPrintf(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, dx=%0.3f, dy=%0.3f, "
308 "pressure=%0.3f, touchMajor=%0.3f, touchMinor=%0.3f, "
309 "toolMajor=%0.3f, toolMinor=%0.3f, "
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700310 "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, "
311 "toolType=%d, isHovering=%s\n",
312 i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(),
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +0000313 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X),
314 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700315 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE),
316 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR),
317 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR),
318 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR),
319 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR),
320 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION),
321 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT),
322 pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE),
323 pointerProperties.toolType,
324 toString(mLastCookedState.cookedPointerData.isHovering(i)));
325 }
326
327 dump += INDENT3 "Stylus Fusion:\n";
328 dump += StringPrintf(INDENT4 "ExternalStylusConnected: %s\n",
329 toString(mExternalStylusConnected));
330 dump += StringPrintf(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId);
331 dump += StringPrintf(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n",
332 mExternalStylusFusionTimeout);
333 dump += INDENT3 "External Stylus State:\n";
334 dumpStylusState(dump, mExternalStylusState);
335
Michael Wrightaff169e2020-07-02 18:30:52 +0100336 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700337 dump += StringPrintf(INDENT3 "Pointer Gesture Detector:\n");
338 dump += StringPrintf(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale);
339 dump += StringPrintf(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale);
340 dump += StringPrintf(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale);
341 dump += StringPrintf(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale);
342 dump += StringPrintf(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth);
343 }
344}
345
346const char* TouchInputMapper::modeToString(DeviceMode deviceMode) {
347 switch (deviceMode) {
Michael Wrightaff169e2020-07-02 18:30:52 +0100348 case DeviceMode::DISABLED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700349 return "disabled";
Michael Wrightaff169e2020-07-02 18:30:52 +0100350 case DeviceMode::DIRECT:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700351 return "direct";
Michael Wrightaff169e2020-07-02 18:30:52 +0100352 case DeviceMode::UNSCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700353 return "unscaled";
Michael Wrightaff169e2020-07-02 18:30:52 +0100354 case DeviceMode::NAVIGATION:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700355 return "navigation";
Michael Wrightaff169e2020-07-02 18:30:52 +0100356 case DeviceMode::POINTER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700357 return "pointer";
358 }
359 return "unknown";
360}
361
362void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config,
363 uint32_t changes) {
364 InputMapper::configure(when, config, changes);
365
366 mConfig = *config;
367
368 if (!changes) { // first time only
369 // Configure basic parameters.
370 configureParameters();
371
372 // Configure common accumulators.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800373 mCursorScrollAccumulator.configure(getDeviceContext());
374 mTouchButtonAccumulator.configure(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700375
376 // Configure absolute axis information.
377 configureRawPointerAxes();
378
379 // Prepare input device calibration.
380 parseCalibration();
381 resolveCalibration();
382 }
383
384 if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) {
385 // Update location calibration to reflect current settings
386 updateAffineTransformation();
387 }
388
389 if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) {
390 // Update pointer speed.
391 mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters);
392 mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
393 mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters);
394 }
395
396 bool resetNeeded = false;
397 if (!changes ||
398 (changes &
399 (InputReaderConfiguration::CHANGE_DISPLAY_INFO |
Nathaniel R. Lewiseba157b2018-02-22 13:31:42 -0800400 InputReaderConfiguration::CHANGE_POINTER_CAPTURE |
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700401 InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT |
402 InputReaderConfiguration::CHANGE_SHOW_TOUCHES |
403 InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) {
404 // Configure device sources, surface dimensions, orientation and
405 // scaling factors.
406 configureSurface(when, &resetNeeded);
407 }
408
409 if (changes && resetNeeded) {
410 // Send reset, unless this is the first time the device has been configured,
411 // in which case the reader will call reset itself after all mappers are ready.
Garfield Tanc51d1ba2020-01-28 13:24:04 -0800412 NotifyDeviceResetArgs args(getContext()->getNextId(), when, getDeviceId());
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800413 getListener()->notifyDeviceReset(&args);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700414 }
415}
416
417void TouchInputMapper::resolveExternalStylusPresence() {
418 std::vector<InputDeviceInfo> devices;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800419 getContext()->getExternalStylusDevices(devices);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700420 mExternalStylusConnected = !devices.empty();
421
422 if (!mExternalStylusConnected) {
423 resetExternalStylus();
424 }
425}
426
427void TouchInputMapper::configureParameters() {
428 // Use the pointer presentation mode for devices that do not support distinct
429 // multitouch. The spot-based presentation relies on being able to accurately
430 // locate two or more fingers on the touch pad.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800431 mParameters.gestureMode = getDeviceContext().hasInputProperty(INPUT_PROP_SEMI_MT)
Michael Wrightaff169e2020-07-02 18:30:52 +0100432 ? Parameters::GestureMode::SINGLE_TOUCH
433 : Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700434
435 String8 gestureModeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800436 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.gestureMode"),
437 gestureModeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700438 if (gestureModeString == "single-touch") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100439 mParameters.gestureMode = Parameters::GestureMode::SINGLE_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700440 } else if (gestureModeString == "multi-touch") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100441 mParameters.gestureMode = Parameters::GestureMode::MULTI_TOUCH;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700442 } else if (gestureModeString != "default") {
443 ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string());
444 }
445 }
446
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800447 if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700448 // The device is a touch screen.
Michael Wrightaff169e2020-07-02 18:30:52 +0100449 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800450 } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700451 // The device is a pointing device like a track pad.
Michael Wrightaff169e2020-07-02 18:30:52 +0100452 mParameters.deviceType = Parameters::DeviceType::POINTER;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800453 } else if (getDeviceContext().hasRelativeAxis(REL_X) ||
454 getDeviceContext().hasRelativeAxis(REL_Y)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700455 // The device is a cursor device with a touch pad attached.
456 // By default don't use the touch pad to move the pointer.
Michael Wrightaff169e2020-07-02 18:30:52 +0100457 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700458 } else {
459 // The device is a touch pad of unknown purpose.
Michael Wrightaff169e2020-07-02 18:30:52 +0100460 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700461 }
462
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800463 mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700464
465 String8 deviceTypeString;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800466 if (getDeviceContext().getConfiguration().tryGetProperty(String8("touch.deviceType"),
467 deviceTypeString)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700468 if (deviceTypeString == "touchScreen") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100469 mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700470 } else if (deviceTypeString == "touchPad") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100471 mParameters.deviceType = Parameters::DeviceType::TOUCH_PAD;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700472 } else if (deviceTypeString == "touchNavigation") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100473 mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700474 } else if (deviceTypeString == "pointer") {
Michael Wrightaff169e2020-07-02 18:30:52 +0100475 mParameters.deviceType = Parameters::DeviceType::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700476 } else if (deviceTypeString != "default") {
477 ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string());
478 }
479 }
480
Michael Wrightaff169e2020-07-02 18:30:52 +0100481 mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800482 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.orientationAware"),
483 mParameters.orientationAware);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700484
485 mParameters.hasAssociatedDisplay = false;
486 mParameters.associatedDisplayIsExternal = false;
487 if (mParameters.orientationAware ||
Michael Wrightaff169e2020-07-02 18:30:52 +0100488 mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
489 mParameters.deviceType == Parameters::DeviceType::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700490 mParameters.hasAssociatedDisplay = true;
Michael Wrightaff169e2020-07-02 18:30:52 +0100491 if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800492 mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700493 String8 uniqueDisplayId;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800494 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.displayId"),
495 uniqueDisplayId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700496 mParameters.uniqueDisplayId = uniqueDisplayId.c_str();
497 }
498 }
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800499 if (getDeviceContext().getAssociatedDisplayPort()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700500 mParameters.hasAssociatedDisplay = true;
501 }
502
503 // Initial downs on external touch devices should wake the device.
504 // Normally we don't do this for internal touch screens to prevent them from waking
505 // up in your pocket but you can enable it using the input device configuration.
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800506 mParameters.wake = getDeviceContext().isExternal();
507 getDeviceContext().getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700508}
509
510void TouchInputMapper::dumpParameters(std::string& dump) {
511 dump += INDENT3 "Parameters:\n";
512
513 switch (mParameters.gestureMode) {
Michael Wrightaff169e2020-07-02 18:30:52 +0100514 case Parameters::GestureMode::SINGLE_TOUCH:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700515 dump += INDENT4 "GestureMode: single-touch\n";
516 break;
Michael Wrightaff169e2020-07-02 18:30:52 +0100517 case Parameters::GestureMode::MULTI_TOUCH:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700518 dump += INDENT4 "GestureMode: multi-touch\n";
519 break;
520 default:
521 assert(false);
522 }
523
524 switch (mParameters.deviceType) {
Michael Wrightaff169e2020-07-02 18:30:52 +0100525 case Parameters::DeviceType::TOUCH_SCREEN:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700526 dump += INDENT4 "DeviceType: touchScreen\n";
527 break;
Michael Wrightaff169e2020-07-02 18:30:52 +0100528 case Parameters::DeviceType::TOUCH_PAD:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700529 dump += INDENT4 "DeviceType: touchPad\n";
530 break;
Michael Wrightaff169e2020-07-02 18:30:52 +0100531 case Parameters::DeviceType::TOUCH_NAVIGATION:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700532 dump += INDENT4 "DeviceType: touchNavigation\n";
533 break;
Michael Wrightaff169e2020-07-02 18:30:52 +0100534 case Parameters::DeviceType::POINTER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700535 dump += INDENT4 "DeviceType: pointer\n";
536 break;
537 default:
538 ALOG_ASSERT(false);
539 }
540
541 dump += StringPrintf(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s, "
542 "displayId='%s'\n",
543 toString(mParameters.hasAssociatedDisplay),
544 toString(mParameters.associatedDisplayIsExternal),
545 mParameters.uniqueDisplayId.c_str());
546 dump += StringPrintf(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware));
547}
548
549void TouchInputMapper::configureRawPointerAxes() {
550 mRawPointerAxes.clear();
551}
552
553void TouchInputMapper::dumpRawPointerAxes(std::string& dump) {
554 dump += INDENT3 "Raw Touch Axes:\n";
555 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X");
556 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y");
557 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure");
558 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor");
559 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor");
560 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor");
561 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor");
562 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation");
563 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance");
564 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX");
565 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY");
566 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId");
567 dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot");
568}
569
570bool TouchInputMapper::hasExternalStylus() const {
571 return mExternalStylusConnected;
572}
573
574/**
575 * Determine which DisplayViewport to use.
576 * 1. If display port is specified, return the matching viewport. If matching viewport not
577 * found, then return.
Garfield Tan888a6a42020-01-09 11:39:16 -0800578 * 2. Always use the suggested viewport from WindowManagerService for pointers.
579 * 3. If a device has associated display, get the matching viewport by either unique id or by
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700580 * the display type (internal or external).
Garfield Tan888a6a42020-01-09 11:39:16 -0800581 * 4. Otherwise, use a non-display viewport.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700582 */
583std::optional<DisplayViewport> TouchInputMapper::findViewport() {
Nathaniel R. Lewiseba157b2018-02-22 13:31:42 -0800584 if (mParameters.hasAssociatedDisplay && mDeviceMode != DeviceMode::UNSCALED) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800585 const std::optional<uint8_t> displayPort = getDeviceContext().getAssociatedDisplayPort();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700586 if (displayPort) {
587 // Find the viewport that contains the same port
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -0800588 return getDeviceContext().getAssociatedViewport();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700589 }
590
Michael Wrightaff169e2020-07-02 18:30:52 +0100591 if (mDeviceMode == DeviceMode::POINTER) {
Garfield Tan888a6a42020-01-09 11:39:16 -0800592 std::optional<DisplayViewport> viewport =
593 mConfig.getDisplayViewportById(mConfig.defaultPointerDisplayId);
594 if (viewport) {
595 return viewport;
596 } else {
597 ALOGW("Can't find designated display viewport with ID %" PRId32 " for pointers.",
598 mConfig.defaultPointerDisplayId);
599 }
600 }
601
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700602 // Check if uniqueDisplayId is specified in idc file.
603 if (!mParameters.uniqueDisplayId.empty()) {
604 return mConfig.getDisplayViewportByUniqueId(mParameters.uniqueDisplayId);
605 }
606
607 ViewportType viewportTypeToUse;
608 if (mParameters.associatedDisplayIsExternal) {
609 viewportTypeToUse = ViewportType::VIEWPORT_EXTERNAL;
610 } else {
611 viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
612 }
613
614 std::optional<DisplayViewport> viewport =
615 mConfig.getDisplayViewportByType(viewportTypeToUse);
616 if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
617 ALOGW("Input device %s should be associated with external display, "
618 "fallback to internal one for the external viewport is not found.",
619 getDeviceName().c_str());
620 viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
621 }
622
623 return viewport;
624 }
625
626 // No associated display, return a non-display viewport.
627 DisplayViewport newViewport;
628 // Raw width and height in the natural orientation.
629 int32_t rawWidth = mRawPointerAxes.getRawWidth();
630 int32_t rawHeight = mRawPointerAxes.getRawHeight();
631 newViewport.setNonDisplayViewport(rawWidth, rawHeight);
632 return std::make_optional(newViewport);
633}
634
635void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) {
Michael Wrightaff169e2020-07-02 18:30:52 +0100636 DeviceMode oldDeviceMode = mDeviceMode;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700637
638 resolveExternalStylusPresence();
639
640 // Determine device mode.
Michael Wrightaff169e2020-07-02 18:30:52 +0100641 if (mParameters.deviceType == Parameters::DeviceType::POINTER &&
Nathaniel R. Lewiseba157b2018-02-22 13:31:42 -0800642 mConfig.pointerGesturesEnabled && !mConfig.pointerCapture) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700643 mSource = AINPUT_SOURCE_MOUSE;
Michael Wrightaff169e2020-07-02 18:30:52 +0100644 mDeviceMode = DeviceMode::POINTER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700645 if (hasStylus()) {
646 mSource |= AINPUT_SOURCE_STYLUS;
647 }
Michael Wrightaff169e2020-07-02 18:30:52 +0100648 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700649 mParameters.hasAssociatedDisplay) {
650 mSource = AINPUT_SOURCE_TOUCHSCREEN;
Michael Wrightaff169e2020-07-02 18:30:52 +0100651 mDeviceMode = DeviceMode::DIRECT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700652 if (hasStylus()) {
653 mSource |= AINPUT_SOURCE_STYLUS;
654 }
655 if (hasExternalStylus()) {
656 mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS;
657 }
Michael Wrightaff169e2020-07-02 18:30:52 +0100658 } else if (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700659 mSource = AINPUT_SOURCE_TOUCH_NAVIGATION;
Michael Wrightaff169e2020-07-02 18:30:52 +0100660 mDeviceMode = DeviceMode::NAVIGATION;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700661 } else {
662 mSource = AINPUT_SOURCE_TOUCHPAD;
Michael Wrightaff169e2020-07-02 18:30:52 +0100663 mDeviceMode = DeviceMode::UNSCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700664 }
665
666 // Ensure we have valid X and Y axes.
667 if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) {
668 ALOGW("Touch device '%s' did not report support for X or Y axis! "
669 "The device will be inoperable.",
670 getDeviceName().c_str());
Michael Wrightaff169e2020-07-02 18:30:52 +0100671 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700672 return;
673 }
674
675 // Get associated display dimensions.
676 std::optional<DisplayViewport> newViewport = findViewport();
677 if (!newViewport) {
678 ALOGI("Touch device '%s' could not query the properties of its associated "
679 "display. The device will be inoperable until the display size "
680 "becomes available.",
681 getDeviceName().c_str());
Michael Wrightaff169e2020-07-02 18:30:52 +0100682 mDeviceMode = DeviceMode::DISABLED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700683 return;
684 }
685
686 // Raw width and height in the natural orientation.
687 int32_t rawWidth = mRawPointerAxes.getRawWidth();
688 int32_t rawHeight = mRawPointerAxes.getRawHeight();
689
690 bool viewportChanged = mViewport != *newViewport;
691 if (viewportChanged) {
692 mViewport = *newViewport;
693
Michael Wrightaff169e2020-07-02 18:30:52 +0100694 if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700695 // Convert rotated viewport to natural surface coordinates.
696 int32_t naturalLogicalWidth, naturalLogicalHeight;
697 int32_t naturalPhysicalWidth, naturalPhysicalHeight;
698 int32_t naturalPhysicalLeft, naturalPhysicalTop;
699 int32_t naturalDeviceWidth, naturalDeviceHeight;
700 switch (mViewport.orientation) {
701 case DISPLAY_ORIENTATION_90:
702 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
703 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
704 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
705 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800706 naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700707 naturalPhysicalTop = mViewport.physicalLeft;
708 naturalDeviceWidth = mViewport.deviceHeight;
709 naturalDeviceHeight = mViewport.deviceWidth;
710 break;
711 case DISPLAY_ORIENTATION_180:
712 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
713 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
714 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
715 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
716 naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight;
717 naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom;
718 naturalDeviceWidth = mViewport.deviceWidth;
719 naturalDeviceHeight = mViewport.deviceHeight;
720 break;
721 case DISPLAY_ORIENTATION_270:
722 naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop;
723 naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft;
724 naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop;
725 naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft;
726 naturalPhysicalLeft = mViewport.physicalTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800727 naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700728 naturalDeviceWidth = mViewport.deviceHeight;
729 naturalDeviceHeight = mViewport.deviceWidth;
730 break;
731 case DISPLAY_ORIENTATION_0:
732 default:
733 naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft;
734 naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop;
735 naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft;
736 naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop;
737 naturalPhysicalLeft = mViewport.physicalLeft;
738 naturalPhysicalTop = mViewport.physicalTop;
739 naturalDeviceWidth = mViewport.deviceWidth;
740 naturalDeviceHeight = mViewport.deviceHeight;
741 break;
742 }
743
744 if (naturalPhysicalHeight == 0 || naturalPhysicalWidth == 0) {
745 ALOGE("Viewport is not set properly: %s", mViewport.toString().c_str());
746 naturalPhysicalHeight = naturalPhysicalHeight == 0 ? 1 : naturalPhysicalHeight;
747 naturalPhysicalWidth = naturalPhysicalWidth == 0 ? 1 : naturalPhysicalWidth;
748 }
749
750 mPhysicalWidth = naturalPhysicalWidth;
751 mPhysicalHeight = naturalPhysicalHeight;
752 mPhysicalLeft = naturalPhysicalLeft;
753 mPhysicalTop = naturalPhysicalTop;
754
Arthur Hung4197f6b2020-03-16 15:39:59 +0800755 mRawSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth;
756 mRawSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700757 mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth;
758 mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800759 mSurfaceRight = mSurfaceLeft + naturalLogicalWidth;
760 mSurfaceBottom = mSurfaceTop + naturalLogicalHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700761
762 mSurfaceOrientation =
763 mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0;
764 } else {
765 mPhysicalWidth = rawWidth;
766 mPhysicalHeight = rawHeight;
767 mPhysicalLeft = 0;
768 mPhysicalTop = 0;
769
Arthur Hung4197f6b2020-03-16 15:39:59 +0800770 mRawSurfaceWidth = rawWidth;
771 mRawSurfaceHeight = rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700772 mSurfaceLeft = 0;
773 mSurfaceTop = 0;
774 mSurfaceOrientation = DISPLAY_ORIENTATION_0;
775 }
776 }
777
778 // If moving between pointer modes, need to reset some state.
779 bool deviceModeChanged = mDeviceMode != oldDeviceMode;
780 if (deviceModeChanged) {
781 mOrientedRanges.clear();
782 }
783
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800784 // Create pointer controller if needed, and keep it around if Pointer Capture is enabled to
785 // preserve the cursor position.
Michael Wrightaff169e2020-07-02 18:30:52 +0100786 if (mDeviceMode == DeviceMode::POINTER ||
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800787 (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches) ||
788 (mParameters.deviceType == Parameters::DeviceType::POINTER && mConfig.pointerCapture)) {
Prabir Pradhanc7ef27e2020-02-03 19:19:15 -0800789 if (mPointerController == nullptr) {
790 mPointerController = getContext()->getPointerController(getDeviceId());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700791 }
Prabir Pradhan59ecc3b2020-11-20 13:11:47 -0800792 if (mConfig.pointerCapture) {
793 mPointerController->fade(PointerControllerInterface::Transition::IMMEDIATE);
794 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700795 } else {
Michael Wright7a376672020-06-26 20:51:44 +0100796 mPointerController.reset();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700797 }
798
799 if (viewportChanged || deviceModeChanged) {
800 ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, "
801 "display id %d",
Arthur Hung4197f6b2020-03-16 15:39:59 +0800802 getDeviceId(), getDeviceName().c_str(), mRawSurfaceWidth, mRawSurfaceHeight,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700803 mSurfaceOrientation, mDeviceMode, mViewport.displayId);
804
805 // Configure X and Y factors.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800806 mXScale = float(mRawSurfaceWidth) / rawWidth;
807 mYScale = float(mRawSurfaceHeight) / rawHeight;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700808 mXTranslate = -mSurfaceLeft;
809 mYTranslate = -mSurfaceTop;
810 mXPrecision = 1.0f / mXScale;
811 mYPrecision = 1.0f / mYScale;
812
813 mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
814 mOrientedRanges.x.source = mSource;
815 mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y;
816 mOrientedRanges.y.source = mSource;
817
818 configureVirtualKeys();
819
820 // Scale factor for terms that are not oriented in a particular axis.
821 // If the pixels are square then xScale == yScale otherwise we fake it
822 // by choosing an average.
823 mGeometricScale = avg(mXScale, mYScale);
824
825 // Size of diagonal axis.
Arthur Hung4197f6b2020-03-16 15:39:59 +0800826 float diagonalSize = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700827
828 // Size factors.
Michael Wrightaff169e2020-07-02 18:30:52 +0100829 if (mCalibration.sizeCalibration != Calibration::SizeCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700830 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) {
831 mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue;
832 } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) {
833 mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue;
834 } else {
835 mSizeScale = 0.0f;
836 }
837
838 mOrientedRanges.haveTouchSize = true;
839 mOrientedRanges.haveToolSize = true;
840 mOrientedRanges.haveSize = true;
841
842 mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR;
843 mOrientedRanges.touchMajor.source = mSource;
844 mOrientedRanges.touchMajor.min = 0;
845 mOrientedRanges.touchMajor.max = diagonalSize;
846 mOrientedRanges.touchMajor.flat = 0;
847 mOrientedRanges.touchMajor.fuzz = 0;
848 mOrientedRanges.touchMajor.resolution = 0;
849
850 mOrientedRanges.touchMinor = mOrientedRanges.touchMajor;
851 mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR;
852
853 mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR;
854 mOrientedRanges.toolMajor.source = mSource;
855 mOrientedRanges.toolMajor.min = 0;
856 mOrientedRanges.toolMajor.max = diagonalSize;
857 mOrientedRanges.toolMajor.flat = 0;
858 mOrientedRanges.toolMajor.fuzz = 0;
859 mOrientedRanges.toolMajor.resolution = 0;
860
861 mOrientedRanges.toolMinor = mOrientedRanges.toolMajor;
862 mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR;
863
864 mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE;
865 mOrientedRanges.size.source = mSource;
866 mOrientedRanges.size.min = 0;
867 mOrientedRanges.size.max = 1.0;
868 mOrientedRanges.size.flat = 0;
869 mOrientedRanges.size.fuzz = 0;
870 mOrientedRanges.size.resolution = 0;
871 } else {
872 mSizeScale = 0.0f;
873 }
874
875 // Pressure factors.
876 mPressureScale = 0;
877 float pressureMax = 1.0;
Michael Wrightaff169e2020-07-02 18:30:52 +0100878 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::PHYSICAL ||
879 mCalibration.pressureCalibration == Calibration::PressureCalibration::AMPLITUDE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700880 if (mCalibration.havePressureScale) {
881 mPressureScale = mCalibration.pressureScale;
882 pressureMax = mPressureScale * mRawPointerAxes.pressure.maxValue;
883 } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) {
884 mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue;
885 }
886 }
887
888 mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE;
889 mOrientedRanges.pressure.source = mSource;
890 mOrientedRanges.pressure.min = 0;
891 mOrientedRanges.pressure.max = pressureMax;
892 mOrientedRanges.pressure.flat = 0;
893 mOrientedRanges.pressure.fuzz = 0;
894 mOrientedRanges.pressure.resolution = 0;
895
896 // Tilt
897 mTiltXCenter = 0;
898 mTiltXScale = 0;
899 mTiltYCenter = 0;
900 mTiltYScale = 0;
901 mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid;
902 if (mHaveTilt) {
903 mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue);
904 mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue);
905 mTiltXScale = M_PI / 180;
906 mTiltYScale = M_PI / 180;
907
Tatsunosuke Tobita35e05532021-06-30 14:49:32 +0900908 if (mRawPointerAxes.tiltX.resolution) {
909 mTiltXScale = 1.0 / mRawPointerAxes.tiltX.resolution;
910 }
911 if (mRawPointerAxes.tiltY.resolution) {
912 mTiltYScale = 1.0 / mRawPointerAxes.tiltY.resolution;
913 }
914
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700915 mOrientedRanges.haveTilt = true;
916
917 mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT;
918 mOrientedRanges.tilt.source = mSource;
919 mOrientedRanges.tilt.min = 0;
920 mOrientedRanges.tilt.max = M_PI_2;
921 mOrientedRanges.tilt.flat = 0;
922 mOrientedRanges.tilt.fuzz = 0;
923 mOrientedRanges.tilt.resolution = 0;
924 }
925
926 // Orientation
927 mOrientationScale = 0;
928 if (mHaveTilt) {
929 mOrientedRanges.haveOrientation = true;
930
931 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
932 mOrientedRanges.orientation.source = mSource;
933 mOrientedRanges.orientation.min = -M_PI;
934 mOrientedRanges.orientation.max = M_PI;
935 mOrientedRanges.orientation.flat = 0;
936 mOrientedRanges.orientation.fuzz = 0;
937 mOrientedRanges.orientation.resolution = 0;
938 } else if (mCalibration.orientationCalibration !=
Michael Wrightaff169e2020-07-02 18:30:52 +0100939 Calibration::OrientationCalibration::NONE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700940 if (mCalibration.orientationCalibration ==
Michael Wrightaff169e2020-07-02 18:30:52 +0100941 Calibration::OrientationCalibration::INTERPOLATED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700942 if (mRawPointerAxes.orientation.valid) {
943 if (mRawPointerAxes.orientation.maxValue > 0) {
944 mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue;
945 } else if (mRawPointerAxes.orientation.minValue < 0) {
946 mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue;
947 } else {
948 mOrientationScale = 0;
949 }
950 }
951 }
952
953 mOrientedRanges.haveOrientation = true;
954
955 mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION;
956 mOrientedRanges.orientation.source = mSource;
957 mOrientedRanges.orientation.min = -M_PI_2;
958 mOrientedRanges.orientation.max = M_PI_2;
959 mOrientedRanges.orientation.flat = 0;
960 mOrientedRanges.orientation.fuzz = 0;
961 mOrientedRanges.orientation.resolution = 0;
962 }
963
964 // Distance
965 mDistanceScale = 0;
Michael Wrightaff169e2020-07-02 18:30:52 +0100966 if (mCalibration.distanceCalibration != Calibration::DistanceCalibration::NONE) {
967 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::SCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700968 if (mCalibration.haveDistanceScale) {
969 mDistanceScale = mCalibration.distanceScale;
970 } else {
971 mDistanceScale = 1.0f;
972 }
973 }
974
975 mOrientedRanges.haveDistance = true;
976
977 mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE;
978 mOrientedRanges.distance.source = mSource;
979 mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale;
980 mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale;
981 mOrientedRanges.distance.flat = 0;
982 mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale;
983 mOrientedRanges.distance.resolution = 0;
984 }
985
986 // Compute oriented precision, scales and ranges.
987 // Note that the maximum value reported is an inclusive maximum value so it is one
988 // unit less than the total width or height of surface.
989 switch (mSurfaceOrientation) {
990 case DISPLAY_ORIENTATION_90:
991 case DISPLAY_ORIENTATION_270:
992 mOrientedXPrecision = mYPrecision;
993 mOrientedYPrecision = mXPrecision;
994
995 mOrientedRanges.x.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +0800996 mOrientedRanges.x.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -0700997 mOrientedRanges.x.flat = 0;
998 mOrientedRanges.x.fuzz = 0;
999 mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
1000
1001 mOrientedRanges.y.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001002 mOrientedRanges.y.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001003 mOrientedRanges.y.flat = 0;
1004 mOrientedRanges.y.fuzz = 0;
1005 mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
1006 break;
1007
1008 default:
1009 mOrientedXPrecision = mXPrecision;
1010 mOrientedYPrecision = mYPrecision;
1011
1012 mOrientedRanges.x.min = mXTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001013 mOrientedRanges.x.max = mRawSurfaceWidth + mXTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001014 mOrientedRanges.x.flat = 0;
1015 mOrientedRanges.x.fuzz = 0;
1016 mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
1017
1018 mOrientedRanges.y.min = mYTranslate;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001019 mOrientedRanges.y.max = mRawSurfaceHeight + mYTranslate - 1;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001020 mOrientedRanges.y.flat = 0;
1021 mOrientedRanges.y.fuzz = 0;
1022 mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
1023 break;
1024 }
1025
1026 // Location
1027 updateAffineTransformation();
1028
Michael Wrightaff169e2020-07-02 18:30:52 +01001029 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001030 // Compute pointer gesture detection parameters.
1031 float rawDiagonal = hypotf(rawWidth, rawHeight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001032 float displayDiagonal = hypotf(mRawSurfaceWidth, mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001033
1034 // Scale movements such that one whole swipe of the touch pad covers a
1035 // given area relative to the diagonal size of the display when no acceleration
1036 // is applied.
1037 // Assume that the touch pad has a square aspect ratio such that movements in
1038 // X and Y of the same number of raw units cover the same physical distance.
1039 mPointerXMovementScale =
1040 mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal;
1041 mPointerYMovementScale = mPointerXMovementScale;
1042
1043 // Scale zooms to cover a smaller range of the display than movements do.
1044 // This value determines the area around the pointer that is affected by freeform
1045 // pointer gestures.
1046 mPointerXZoomScale =
1047 mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal;
1048 mPointerYZoomScale = mPointerXZoomScale;
1049
1050 // Max width between pointers to detect a swipe gesture is more than some fraction
1051 // of the diagonal axis of the touch pad. Touches that are wider than this are
1052 // translated into freeform gestures.
1053 mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal;
1054
1055 // Abort current pointer usages because the state has changed.
1056 abortPointerUsage(when, 0 /*policyFlags*/);
1057 }
1058
1059 // Inform the dispatcher about the changes.
1060 *outResetNeeded = true;
1061 bumpGeneration();
1062 }
1063}
1064
1065void TouchInputMapper::dumpSurface(std::string& dump) {
1066 dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
Arthur Hung4197f6b2020-03-16 15:39:59 +08001067 dump += StringPrintf(INDENT3 "RawSurfaceWidth: %dpx\n", mRawSurfaceWidth);
1068 dump += StringPrintf(INDENT3 "RawSurfaceHeight: %dpx\n", mRawSurfaceHeight);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001069 dump += StringPrintf(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft);
1070 dump += StringPrintf(INDENT3 "SurfaceTop: %d\n", mSurfaceTop);
Arthur Hung4197f6b2020-03-16 15:39:59 +08001071 dump += StringPrintf(INDENT3 "SurfaceRight: %d\n", mSurfaceRight);
1072 dump += StringPrintf(INDENT3 "SurfaceBottom: %d\n", mSurfaceBottom);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001073 dump += StringPrintf(INDENT3 "PhysicalWidth: %dpx\n", mPhysicalWidth);
1074 dump += StringPrintf(INDENT3 "PhysicalHeight: %dpx\n", mPhysicalHeight);
1075 dump += StringPrintf(INDENT3 "PhysicalLeft: %d\n", mPhysicalLeft);
1076 dump += StringPrintf(INDENT3 "PhysicalTop: %d\n", mPhysicalTop);
1077 dump += StringPrintf(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation);
1078}
1079
1080void TouchInputMapper::configureVirtualKeys() {
1081 std::vector<VirtualKeyDefinition> virtualKeyDefinitions;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001082 getDeviceContext().getVirtualKeyDefinitions(virtualKeyDefinitions);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001083
1084 mVirtualKeys.clear();
1085
1086 if (virtualKeyDefinitions.size() == 0) {
1087 return;
1088 }
1089
1090 int32_t touchScreenLeft = mRawPointerAxes.x.minValue;
1091 int32_t touchScreenTop = mRawPointerAxes.y.minValue;
1092 int32_t touchScreenWidth = mRawPointerAxes.getRawWidth();
1093 int32_t touchScreenHeight = mRawPointerAxes.getRawHeight();
1094
1095 for (const VirtualKeyDefinition& virtualKeyDefinition : virtualKeyDefinitions) {
1096 VirtualKey virtualKey;
1097
1098 virtualKey.scanCode = virtualKeyDefinition.scanCode;
1099 int32_t keyCode;
1100 int32_t dummyKeyMetaState;
1101 uint32_t flags;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001102 if (getDeviceContext().mapKey(virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState,
1103 &flags)) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001104 ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode);
1105 continue; // drop the key
1106 }
1107
1108 virtualKey.keyCode = keyCode;
1109 virtualKey.flags = flags;
1110
1111 // convert the key definition's display coordinates into touch coordinates for a hit box
1112 int32_t halfWidth = virtualKeyDefinition.width / 2;
1113 int32_t halfHeight = virtualKeyDefinition.height / 2;
1114
1115 virtualKey.hitLeft =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001116 (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001117 touchScreenLeft;
1118 virtualKey.hitRight =
Arthur Hung4197f6b2020-03-16 15:39:59 +08001119 (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mRawSurfaceWidth +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001120 touchScreenLeft;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001121 virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight /
1122 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001123 touchScreenTop;
Arthur Hung4197f6b2020-03-16 15:39:59 +08001124 virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight /
1125 mRawSurfaceHeight +
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001126 touchScreenTop;
1127 mVirtualKeys.push_back(virtualKey);
1128 }
1129}
1130
1131void TouchInputMapper::dumpVirtualKeys(std::string& dump) {
1132 if (!mVirtualKeys.empty()) {
1133 dump += INDENT3 "Virtual Keys:\n";
1134
1135 for (size_t i = 0; i < mVirtualKeys.size(); i++) {
1136 const VirtualKey& virtualKey = mVirtualKeys[i];
1137 dump += StringPrintf(INDENT4 "%zu: scanCode=%d, keyCode=%d, "
1138 "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n",
1139 i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft,
1140 virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom);
1141 }
1142 }
1143}
1144
1145void TouchInputMapper::parseCalibration() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001146 const PropertyMap& in = getDeviceContext().getConfiguration();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001147 Calibration& out = mCalibration;
1148
1149 // Size
Michael Wrightaff169e2020-07-02 18:30:52 +01001150 out.sizeCalibration = Calibration::SizeCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001151 String8 sizeCalibrationString;
1152 if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) {
1153 if (sizeCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001154 out.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001155 } else if (sizeCalibrationString == "geometric") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001156 out.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001157 } else if (sizeCalibrationString == "diameter") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001158 out.sizeCalibration = Calibration::SizeCalibration::DIAMETER;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001159 } else if (sizeCalibrationString == "box") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001160 out.sizeCalibration = Calibration::SizeCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001161 } else if (sizeCalibrationString == "area") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001162 out.sizeCalibration = Calibration::SizeCalibration::AREA;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001163 } else if (sizeCalibrationString != "default") {
1164 ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string());
1165 }
1166 }
1167
1168 out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale);
1169 out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias);
1170 out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed);
1171
1172 // Pressure
Michael Wrightaff169e2020-07-02 18:30:52 +01001173 out.pressureCalibration = Calibration::PressureCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001174 String8 pressureCalibrationString;
1175 if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) {
1176 if (pressureCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001177 out.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001178 } else if (pressureCalibrationString == "physical") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001179 out.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001180 } else if (pressureCalibrationString == "amplitude") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001181 out.pressureCalibration = Calibration::PressureCalibration::AMPLITUDE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001182 } else if (pressureCalibrationString != "default") {
1183 ALOGW("Invalid value for touch.pressure.calibration: '%s'",
1184 pressureCalibrationString.string());
1185 }
1186 }
1187
1188 out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale);
1189
1190 // Orientation
Michael Wrightaff169e2020-07-02 18:30:52 +01001191 out.orientationCalibration = Calibration::OrientationCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001192 String8 orientationCalibrationString;
1193 if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) {
1194 if (orientationCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001195 out.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001196 } else if (orientationCalibrationString == "interpolated") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001197 out.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001198 } else if (orientationCalibrationString == "vector") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001199 out.orientationCalibration = Calibration::OrientationCalibration::VECTOR;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001200 } else if (orientationCalibrationString != "default") {
1201 ALOGW("Invalid value for touch.orientation.calibration: '%s'",
1202 orientationCalibrationString.string());
1203 }
1204 }
1205
1206 // Distance
Michael Wrightaff169e2020-07-02 18:30:52 +01001207 out.distanceCalibration = Calibration::DistanceCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001208 String8 distanceCalibrationString;
1209 if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) {
1210 if (distanceCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001211 out.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001212 } else if (distanceCalibrationString == "scaled") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001213 out.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001214 } else if (distanceCalibrationString != "default") {
1215 ALOGW("Invalid value for touch.distance.calibration: '%s'",
1216 distanceCalibrationString.string());
1217 }
1218 }
1219
1220 out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale);
1221
Michael Wrightaff169e2020-07-02 18:30:52 +01001222 out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001223 String8 coverageCalibrationString;
1224 if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) {
1225 if (coverageCalibrationString == "none") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001226 out.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001227 } else if (coverageCalibrationString == "box") {
Michael Wrightaff169e2020-07-02 18:30:52 +01001228 out.coverageCalibration = Calibration::CoverageCalibration::BOX;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001229 } else if (coverageCalibrationString != "default") {
1230 ALOGW("Invalid value for touch.coverage.calibration: '%s'",
1231 coverageCalibrationString.string());
1232 }
1233 }
1234}
1235
1236void TouchInputMapper::resolveCalibration() {
1237 // Size
1238 if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001239 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DEFAULT) {
1240 mCalibration.sizeCalibration = Calibration::SizeCalibration::GEOMETRIC;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001241 }
1242 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001243 mCalibration.sizeCalibration = Calibration::SizeCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001244 }
1245
1246 // Pressure
1247 if (mRawPointerAxes.pressure.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001248 if (mCalibration.pressureCalibration == Calibration::PressureCalibration::DEFAULT) {
1249 mCalibration.pressureCalibration = Calibration::PressureCalibration::PHYSICAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001250 }
1251 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001252 mCalibration.pressureCalibration = Calibration::PressureCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001253 }
1254
1255 // Orientation
1256 if (mRawPointerAxes.orientation.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001257 if (mCalibration.orientationCalibration == Calibration::OrientationCalibration::DEFAULT) {
1258 mCalibration.orientationCalibration = Calibration::OrientationCalibration::INTERPOLATED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001259 }
1260 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001261 mCalibration.orientationCalibration = Calibration::OrientationCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001262 }
1263
1264 // Distance
1265 if (mRawPointerAxes.distance.valid) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001266 if (mCalibration.distanceCalibration == Calibration::DistanceCalibration::DEFAULT) {
1267 mCalibration.distanceCalibration = Calibration::DistanceCalibration::SCALED;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001268 }
1269 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001270 mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001271 }
1272
1273 // Coverage
Michael Wrightaff169e2020-07-02 18:30:52 +01001274 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
1275 mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001276 }
1277}
1278
1279void TouchInputMapper::dumpCalibration(std::string& dump) {
1280 dump += INDENT3 "Calibration:\n";
1281
1282 // Size
1283 switch (mCalibration.sizeCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001284 case Calibration::SizeCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001285 dump += INDENT4 "touch.size.calibration: none\n";
1286 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001287 case Calibration::SizeCalibration::GEOMETRIC:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001288 dump += INDENT4 "touch.size.calibration: geometric\n";
1289 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001290 case Calibration::SizeCalibration::DIAMETER:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001291 dump += INDENT4 "touch.size.calibration: diameter\n";
1292 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001293 case Calibration::SizeCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001294 dump += INDENT4 "touch.size.calibration: box\n";
1295 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001296 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001297 dump += INDENT4 "touch.size.calibration: area\n";
1298 break;
1299 default:
1300 ALOG_ASSERT(false);
1301 }
1302
1303 if (mCalibration.haveSizeScale) {
1304 dump += StringPrintf(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale);
1305 }
1306
1307 if (mCalibration.haveSizeBias) {
1308 dump += StringPrintf(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias);
1309 }
1310
1311 if (mCalibration.haveSizeIsSummed) {
1312 dump += StringPrintf(INDENT4 "touch.size.isSummed: %s\n",
1313 toString(mCalibration.sizeIsSummed));
1314 }
1315
1316 // Pressure
1317 switch (mCalibration.pressureCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001318 case Calibration::PressureCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001319 dump += INDENT4 "touch.pressure.calibration: none\n";
1320 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001321 case Calibration::PressureCalibration::PHYSICAL:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001322 dump += INDENT4 "touch.pressure.calibration: physical\n";
1323 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001324 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001325 dump += INDENT4 "touch.pressure.calibration: amplitude\n";
1326 break;
1327 default:
1328 ALOG_ASSERT(false);
1329 }
1330
1331 if (mCalibration.havePressureScale) {
1332 dump += StringPrintf(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale);
1333 }
1334
1335 // Orientation
1336 switch (mCalibration.orientationCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001337 case Calibration::OrientationCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001338 dump += INDENT4 "touch.orientation.calibration: none\n";
1339 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001340 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001341 dump += INDENT4 "touch.orientation.calibration: interpolated\n";
1342 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001343 case Calibration::OrientationCalibration::VECTOR:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001344 dump += INDENT4 "touch.orientation.calibration: vector\n";
1345 break;
1346 default:
1347 ALOG_ASSERT(false);
1348 }
1349
1350 // Distance
1351 switch (mCalibration.distanceCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001352 case Calibration::DistanceCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001353 dump += INDENT4 "touch.distance.calibration: none\n";
1354 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001355 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001356 dump += INDENT4 "touch.distance.calibration: scaled\n";
1357 break;
1358 default:
1359 ALOG_ASSERT(false);
1360 }
1361
1362 if (mCalibration.haveDistanceScale) {
1363 dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale);
1364 }
1365
1366 switch (mCalibration.coverageCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001367 case Calibration::CoverageCalibration::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001368 dump += INDENT4 "touch.coverage.calibration: none\n";
1369 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01001370 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001371 dump += INDENT4 "touch.coverage.calibration: box\n";
1372 break;
1373 default:
1374 ALOG_ASSERT(false);
1375 }
1376}
1377
1378void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
1379 dump += INDENT3 "Affine Transformation:\n";
1380
1381 dump += StringPrintf(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale);
1382 dump += StringPrintf(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix);
1383 dump += StringPrintf(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset);
1384 dump += StringPrintf(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix);
1385 dump += StringPrintf(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale);
1386 dump += StringPrintf(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset);
1387}
1388
1389void TouchInputMapper::updateAffineTransformation() {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001390 mAffineTransform = getPolicy()->getTouchAffineTransformation(getDeviceContext().getDescriptor(),
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001391 mSurfaceOrientation);
1392}
1393
1394void TouchInputMapper::reset(nsecs_t when) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001395 mCursorButtonAccumulator.reset(getDeviceContext());
1396 mCursorScrollAccumulator.reset(getDeviceContext());
1397 mTouchButtonAccumulator.reset(getDeviceContext());
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001398
1399 mPointerVelocityControl.reset();
1400 mWheelXVelocityControl.reset();
1401 mWheelYVelocityControl.reset();
1402
1403 mRawStatesPending.clear();
1404 mCurrentRawState.clear();
1405 mCurrentCookedState.clear();
1406 mLastRawState.clear();
1407 mLastCookedState.clear();
Michael Wrightaff169e2020-07-02 18:30:52 +01001408 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001409 mSentHoverEnter = false;
1410 mHavePointerIds = false;
1411 mCurrentMotionAborted = false;
1412 mDownTime = 0;
1413
1414 mCurrentVirtualKey.down = false;
1415
1416 mPointerGesture.reset();
1417 mPointerSimple.reset();
1418 resetExternalStylus();
1419
1420 if (mPointerController != nullptr) {
Michael Wright976db0c2020-07-02 00:00:29 +01001421 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001422 mPointerController->clearSpots();
1423 }
1424
1425 InputMapper::reset(when);
1426}
1427
1428void TouchInputMapper::resetExternalStylus() {
1429 mExternalStylusState.clear();
1430 mExternalStylusId = -1;
1431 mExternalStylusFusionTimeout = LLONG_MAX;
1432 mExternalStylusDataPending = false;
1433}
1434
1435void TouchInputMapper::clearStylusDataPendingFlags() {
1436 mExternalStylusDataPending = false;
1437 mExternalStylusFusionTimeout = LLONG_MAX;
1438}
1439
1440void TouchInputMapper::process(const RawEvent* rawEvent) {
1441 mCursorButtonAccumulator.process(rawEvent);
1442 mCursorScrollAccumulator.process(rawEvent);
1443 mTouchButtonAccumulator.process(rawEvent);
1444
1445 if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
1446 sync(rawEvent->when);
1447 }
1448}
1449
1450void TouchInputMapper::sync(nsecs_t when) {
1451 const RawState* last =
1452 mRawStatesPending.empty() ? &mCurrentRawState : &mRawStatesPending.back();
1453
1454 // Push a new state.
1455 mRawStatesPending.emplace_back();
1456
1457 RawState* next = &mRawStatesPending.back();
1458 next->clear();
1459 next->when = when;
1460
1461 // Sync button state.
1462 next->buttonState =
1463 mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState();
1464
1465 // Sync scroll
1466 next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel();
1467 next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel();
1468 mCursorScrollAccumulator.finishSync();
1469
1470 // Sync touch
1471 syncTouch(when, next);
1472
1473 // Assign pointer ids.
1474 if (!mHavePointerIds) {
1475 assignPointerIds(last, next);
1476 }
1477
1478#if DEBUG_RAW_EVENTS
1479 ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, "
arthurhung65600042020-04-30 17:55:40 +08001480 "hovering ids 0x%08x -> 0x%08x, canceled ids 0x%08x",
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001481 last->rawPointerData.pointerCount, next->rawPointerData.pointerCount,
1482 last->rawPointerData.touchingIdBits.value, next->rawPointerData.touchingIdBits.value,
arthurhung65600042020-04-30 17:55:40 +08001483 last->rawPointerData.hoveringIdBits.value, next->rawPointerData.hoveringIdBits.value,
1484 next->rawPointerData.canceledIdBits.value);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001485#endif
1486
1487 processRawTouches(false /*timeout*/);
1488}
1489
1490void TouchInputMapper::processRawTouches(bool timeout) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001491 if (mDeviceMode == DeviceMode::DISABLED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001492 // Drop all input if the device is disabled.
1493 mCurrentRawState.clear();
1494 mRawStatesPending.clear();
1495 return;
1496 }
1497
1498 // Drain any pending touch states. The invariant here is that the mCurrentRawState is always
1499 // valid and must go through the full cook and dispatch cycle. This ensures that anything
1500 // touching the current state will only observe the events that have been dispatched to the
1501 // rest of the pipeline.
1502 const size_t N = mRawStatesPending.size();
1503 size_t count;
1504 for (count = 0; count < N; count++) {
1505 const RawState& next = mRawStatesPending[count];
1506
1507 // A failure to assign the stylus id means that we're waiting on stylus data
1508 // and so should defer the rest of the pipeline.
1509 if (assignExternalStylusId(next, timeout)) {
1510 break;
1511 }
1512
1513 // All ready to go.
1514 clearStylusDataPendingFlags();
1515 mCurrentRawState.copyFrom(next);
1516 if (mCurrentRawState.when < mLastRawState.when) {
1517 mCurrentRawState.when = mLastRawState.when;
1518 }
1519 cookAndDispatch(mCurrentRawState.when);
1520 }
1521 if (count != 0) {
1522 mRawStatesPending.erase(mRawStatesPending.begin(), mRawStatesPending.begin() + count);
1523 }
1524
1525 if (mExternalStylusDataPending) {
1526 if (timeout) {
1527 nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY;
1528 clearStylusDataPendingFlags();
1529 mCurrentRawState.copyFrom(mLastRawState);
1530#if DEBUG_STYLUS_FUSION
1531 ALOGD("Timeout expired, synthesizing event with new stylus data");
1532#endif
1533 cookAndDispatch(when);
1534 } else if (mExternalStylusFusionTimeout == LLONG_MAX) {
1535 mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT;
1536 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1537 }
1538 }
1539}
1540
1541void TouchInputMapper::cookAndDispatch(nsecs_t when) {
1542 // Always start with a clean state.
1543 mCurrentCookedState.clear();
1544
1545 // Apply stylus buttons to current raw state.
1546 applyExternalStylusButtonState(when);
1547
1548 // Handle policy on initial down or hover events.
1549 bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1550 mCurrentRawState.rawPointerData.pointerCount != 0;
1551
1552 uint32_t policyFlags = 0;
1553 bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState;
1554 if (initialDown || buttonsPressed) {
1555 // If this is a touch screen, hide the pointer on an initial down.
Michael Wrightaff169e2020-07-02 18:30:52 +01001556 if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001557 getContext()->fadePointer();
1558 }
1559
1560 if (mParameters.wake) {
1561 policyFlags |= POLICY_FLAG_WAKE;
1562 }
1563 }
1564
1565 // Consume raw off-screen touches before cooking pointer data.
1566 // If touches are consumed, subsequent code will not receive any pointer data.
1567 if (consumeRawTouches(when, policyFlags)) {
1568 mCurrentRawState.rawPointerData.clear();
1569 }
1570
1571 // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure
1572 // with cooked pointer data that has the same ids and indices as the raw data.
1573 // The following code can use either the raw or cooked data, as needed.
1574 cookPointerData();
1575
1576 // Apply stylus pressure to current cooked state.
1577 applyExternalStylusTouchState(when);
1578
1579 // Synthesize key down from raw buttons if needed.
1580 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource,
1581 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1582 mCurrentCookedState.buttonState);
1583
1584 // Dispatch the touches either directly or by translation through a pointer on screen.
Michael Wrightaff169e2020-07-02 18:30:52 +01001585 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001586 for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty();) {
1587 uint32_t id = idBits.clearFirstMarkedBit();
1588 const RawPointerData::Pointer& pointer =
1589 mCurrentRawState.rawPointerData.pointerForId(id);
1590 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1591 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1592 mCurrentCookedState.stylusIdBits.markBit(id);
1593 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER ||
1594 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1595 mCurrentCookedState.fingerIdBits.markBit(id);
1596 } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) {
1597 mCurrentCookedState.mouseIdBits.markBit(id);
1598 }
1599 }
1600 for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty();) {
1601 uint32_t id = idBits.clearFirstMarkedBit();
1602 const RawPointerData::Pointer& pointer =
1603 mCurrentRawState.rawPointerData.pointerForId(id);
1604 if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS ||
1605 pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) {
1606 mCurrentCookedState.stylusIdBits.markBit(id);
1607 }
1608 }
1609
1610 // Stylus takes precedence over all tools, then mouse, then finger.
1611 PointerUsage pointerUsage = mPointerUsage;
1612 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
1613 mCurrentCookedState.mouseIdBits.clear();
1614 mCurrentCookedState.fingerIdBits.clear();
Michael Wrightaff169e2020-07-02 18:30:52 +01001615 pointerUsage = PointerUsage::STYLUS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001616 } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
1617 mCurrentCookedState.fingerIdBits.clear();
Michael Wrightaff169e2020-07-02 18:30:52 +01001618 pointerUsage = PointerUsage::MOUSE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001619 } else if (!mCurrentCookedState.fingerIdBits.isEmpty() ||
1620 isPointerDown(mCurrentRawState.buttonState)) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001621 pointerUsage = PointerUsage::GESTURES;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001622 }
1623
1624 dispatchPointerUsage(when, policyFlags, pointerUsage);
1625 } else {
Michael Wrightaff169e2020-07-02 18:30:52 +01001626 if (mDeviceMode == DeviceMode::DIRECT && mConfig.showTouches &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001627 mPointerController != nullptr) {
Michael Wright976db0c2020-07-02 00:00:29 +01001628 mPointerController->setPresentation(PointerControllerInterface::Presentation::SPOT);
1629 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001630
1631 mPointerController->setButtonState(mCurrentRawState.buttonState);
1632 mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords,
1633 mCurrentCookedState.cookedPointerData.idToIndex,
1634 mCurrentCookedState.cookedPointerData.touchingIdBits,
1635 mViewport.displayId);
1636 }
1637
1638 if (!mCurrentMotionAborted) {
1639 dispatchButtonRelease(when, policyFlags);
1640 dispatchHoverExit(when, policyFlags);
1641 dispatchTouches(when, policyFlags);
1642 dispatchHoverEnterAndMove(when, policyFlags);
1643 dispatchButtonPress(when, policyFlags);
1644 }
1645
1646 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
1647 mCurrentMotionAborted = false;
1648 }
1649 }
1650
1651 // Synthesize key up from raw buttons if needed.
1652 synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource,
1653 mViewport.displayId, policyFlags, mLastCookedState.buttonState,
1654 mCurrentCookedState.buttonState);
1655
1656 // Clear some transient state.
1657 mCurrentRawState.rawVScroll = 0;
1658 mCurrentRawState.rawHScroll = 0;
1659
1660 // Copy current touch to last touch in preparation for the next cycle.
1661 mLastRawState.copyFrom(mCurrentRawState);
1662 mLastCookedState.copyFrom(mCurrentCookedState);
1663}
1664
1665void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001666 if (mDeviceMode == DeviceMode::DIRECT && hasExternalStylus() && mExternalStylusId != -1) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001667 mCurrentRawState.buttonState |= mExternalStylusState.buttons;
1668 }
1669}
1670
1671void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) {
1672 CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData;
1673 const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData;
1674
1675 if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) {
1676 float pressure = mExternalStylusState.pressure;
1677 if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) {
1678 const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId);
1679 pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
1680 }
1681 PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId);
1682 coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
1683
1684 PointerProperties& properties =
1685 currentPointerData.editPointerPropertiesWithId(mExternalStylusId);
1686 if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) {
1687 properties.toolType = mExternalStylusState.toolType;
1688 }
1689 }
1690}
1691
1692bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001693 if (mDeviceMode != DeviceMode::DIRECT || !hasExternalStylus()) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001694 return false;
1695 }
1696
1697 const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 &&
1698 state.rawPointerData.pointerCount != 0;
1699 if (initialDown) {
1700 if (mExternalStylusState.pressure != 0.0f) {
1701#if DEBUG_STYLUS_FUSION
1702 ALOGD("Have both stylus and touch data, beginning fusion");
1703#endif
1704 mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit();
1705 } else if (timeout) {
1706#if DEBUG_STYLUS_FUSION
1707 ALOGD("Timeout expired, assuming touch is not a stylus.");
1708#endif
1709 resetExternalStylus();
1710 } else {
1711 if (mExternalStylusFusionTimeout == LLONG_MAX) {
1712 mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT;
1713 }
1714#if DEBUG_STYLUS_FUSION
1715 ALOGD("No stylus data but stylus is connected, requesting timeout "
1716 "(%" PRId64 "ms)",
1717 mExternalStylusFusionTimeout);
1718#endif
1719 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1720 return true;
1721 }
1722 }
1723
1724 // Check if the stylus pointer has gone up.
1725 if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) {
1726#if DEBUG_STYLUS_FUSION
1727 ALOGD("Stylus pointer is going up");
1728#endif
1729 mExternalStylusId = -1;
1730 }
1731
1732 return false;
1733}
1734
1735void TouchInputMapper::timeoutExpired(nsecs_t when) {
Michael Wrightaff169e2020-07-02 18:30:52 +01001736 if (mDeviceMode == DeviceMode::POINTER) {
1737 if (mPointerUsage == PointerUsage::GESTURES) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001738 dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/);
1739 }
Michael Wrightaff169e2020-07-02 18:30:52 +01001740 } else if (mDeviceMode == DeviceMode::DIRECT) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001741 if (mExternalStylusFusionTimeout < when) {
1742 processRawTouches(true /*timeout*/);
1743 } else if (mExternalStylusFusionTimeout != LLONG_MAX) {
1744 getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout);
1745 }
1746 }
1747}
1748
1749void TouchInputMapper::updateExternalStylusState(const StylusState& state) {
1750 mExternalStylusState.copyFrom(state);
1751 if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) {
1752 // We're either in the middle of a fused stream of data or we're waiting on data before
1753 // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus
1754 // data.
1755 mExternalStylusDataPending = true;
1756 processRawTouches(false /*timeout*/);
1757 }
1758}
1759
1760bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) {
1761 // Check for release of a virtual key.
1762 if (mCurrentVirtualKey.down) {
1763 if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1764 // Pointer went up while virtual key was down.
1765 mCurrentVirtualKey.down = false;
1766 if (!mCurrentVirtualKey.ignored) {
1767#if DEBUG_VIRTUAL_KEYS
1768 ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d",
1769 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1770#endif
1771 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1772 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1773 }
1774 return true;
1775 }
1776
1777 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1778 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1779 const RawPointerData::Pointer& pointer =
1780 mCurrentRawState.rawPointerData.pointerForId(id);
1781 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1782 if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) {
1783 // Pointer is still within the space of the virtual key.
1784 return true;
1785 }
1786 }
1787
1788 // Pointer left virtual key area or another pointer also went down.
1789 // Send key cancellation but do not consume the touch yet.
1790 // This is useful when the user swipes through from the virtual key area
1791 // into the main display surface.
1792 mCurrentVirtualKey.down = false;
1793 if (!mCurrentVirtualKey.ignored) {
1794#if DEBUG_VIRTUAL_KEYS
1795 ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode,
1796 mCurrentVirtualKey.scanCode);
1797#endif
1798 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP,
1799 AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY |
1800 AKEY_EVENT_FLAG_CANCELED);
1801 }
1802 }
1803
1804 if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() &&
1805 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
1806 // Pointer just went down. Check for virtual key press or off-screen touches.
1807 uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit();
1808 const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id);
Chris Yedca44af2020-08-05 15:07:56 -07001809 // Exclude unscaled device for inside surface checking.
1810 if (!isPointInsideSurface(pointer.x, pointer.y) && mDeviceMode != DeviceMode::UNSCALED) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001811 // If exactly one pointer went down, check for virtual key hit.
1812 // Otherwise we will drop the entire stroke.
1813 if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) {
1814 const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y);
1815 if (virtualKey) {
1816 mCurrentVirtualKey.down = true;
1817 mCurrentVirtualKey.downTime = when;
1818 mCurrentVirtualKey.keyCode = virtualKey->keyCode;
1819 mCurrentVirtualKey.scanCode = virtualKey->scanCode;
1820 mCurrentVirtualKey.ignored =
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001821 getContext()->shouldDropVirtualKey(when, virtualKey->keyCode,
1822 virtualKey->scanCode);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001823
1824 if (!mCurrentVirtualKey.ignored) {
1825#if DEBUG_VIRTUAL_KEYS
1826 ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d",
1827 mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode);
1828#endif
1829 dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN,
1830 AKEY_EVENT_FLAG_FROM_SYSTEM |
1831 AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY);
1832 }
1833 }
1834 }
1835 return true;
1836 }
1837 }
1838
1839 // Disable all virtual key touches that happen within a short time interval of the
1840 // most recent touch within the screen area. The idea is to filter out stray
1841 // virtual key presses when interacting with the touch screen.
1842 //
1843 // Problems we're trying to solve:
1844 //
1845 // 1. While scrolling a list or dragging the window shade, the user swipes down into a
1846 // virtual key area that is implemented by a separate touch panel and accidentally
1847 // triggers a virtual key.
1848 //
1849 // 2. While typing in the on screen keyboard, the user taps slightly outside the screen
1850 // area and accidentally triggers a virtual key. This often happens when virtual keys
1851 // are layed out below the screen near to where the on screen keyboard's space bar
1852 // is displayed.
1853 if (mConfig.virtualKeyQuietTime > 0 &&
1854 !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) {
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001855 getContext()->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001856 }
1857 return false;
1858}
1859
1860void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags,
1861 int32_t keyEventAction, int32_t keyEventFlags) {
1862 int32_t keyCode = mCurrentVirtualKey.keyCode;
1863 int32_t scanCode = mCurrentVirtualKey.scanCode;
1864 nsecs_t downTime = mCurrentVirtualKey.downTime;
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08001865 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001866 policyFlags |= POLICY_FLAG_VIRTUAL;
1867
Garfield Tanc51d1ba2020-01-28 13:24:04 -08001868 NotifyKeyArgs args(getContext()->getNextId(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
1869 mViewport.displayId, policyFlags, keyEventAction, keyEventFlags, keyCode,
1870 scanCode, metaState, downTime);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001871 getListener()->notifyKey(&args);
1872}
1873
1874void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) {
1875 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1876 if (!currentIdBits.isEmpty()) {
1877 int32_t metaState = getContext()->getGlobalMetaState();
1878 int32_t buttonState = mCurrentCookedState.buttonState;
1879 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
1880 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1881 mCurrentCookedState.cookedPointerData.pointerProperties,
1882 mCurrentCookedState.cookedPointerData.pointerCoords,
1883 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1884 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1885 mCurrentMotionAborted = true;
1886 }
1887}
1888
1889void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) {
1890 BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits;
1891 BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits;
1892 int32_t metaState = getContext()->getGlobalMetaState();
1893 int32_t buttonState = mCurrentCookedState.buttonState;
1894
1895 if (currentIdBits == lastIdBits) {
1896 if (!currentIdBits.isEmpty()) {
1897 // No pointer id changes so this is a move event.
1898 // The listener takes care of batching moves so we don't have to deal with that here.
1899 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1900 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
1901 mCurrentCookedState.cookedPointerData.pointerProperties,
1902 mCurrentCookedState.cookedPointerData.pointerCoords,
1903 mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1,
1904 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1905 }
1906 } else {
1907 // There may be pointers going up and pointers going down and pointers moving
1908 // all at the same time.
1909 BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value);
1910 BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value);
1911 BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value);
1912 BitSet32 dispatchedIdBits(lastIdBits.value);
1913
1914 // Update last coordinates of pointers that have moved so that we observe the new
1915 // pointer positions at the same time as other pointers that have just gone up.
1916 bool moveNeeded =
1917 updateMovedPointers(mCurrentCookedState.cookedPointerData.pointerProperties,
1918 mCurrentCookedState.cookedPointerData.pointerCoords,
1919 mCurrentCookedState.cookedPointerData.idToIndex,
1920 mLastCookedState.cookedPointerData.pointerProperties,
1921 mLastCookedState.cookedPointerData.pointerCoords,
1922 mLastCookedState.cookedPointerData.idToIndex, moveIdBits);
1923 if (buttonState != mLastCookedState.buttonState) {
1924 moveNeeded = true;
1925 }
1926
1927 // Dispatch pointer up events.
1928 while (!upIdBits.isEmpty()) {
1929 uint32_t upId = upIdBits.clearFirstMarkedBit();
arthurhung65600042020-04-30 17:55:40 +08001930 bool isCanceled = mCurrentCookedState.cookedPointerData.canceledIdBits.hasBit(upId);
1931 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0,
1932 isCanceled ? AMOTION_EVENT_FLAG_CANCELED : 0, metaState, buttonState, 0,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001933 mLastCookedState.cookedPointerData.pointerProperties,
1934 mLastCookedState.cookedPointerData.pointerCoords,
1935 mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId,
1936 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1937 dispatchedIdBits.clearBit(upId);
arthurhung65600042020-04-30 17:55:40 +08001938 mCurrentCookedState.cookedPointerData.canceledIdBits.clearBit(upId);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07001939 }
1940
1941 // Dispatch move events if any of the remaining pointers moved from their old locations.
1942 // Although applications receive new locations as part of individual pointer up
1943 // events, they do not generally handle them except when presented in a move event.
1944 if (moveNeeded && !moveIdBits.isEmpty()) {
1945 ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value);
1946 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
1947 buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties,
1948 mCurrentCookedState.cookedPointerData.pointerCoords,
1949 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1,
1950 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1951 }
1952
1953 // Dispatch pointer down events using the new pointer locations.
1954 while (!downIdBits.isEmpty()) {
1955 uint32_t downId = downIdBits.clearFirstMarkedBit();
1956 dispatchedIdBits.markBit(downId);
1957
1958 if (dispatchedIdBits.count() == 1) {
1959 // First pointer is going down. Set down time.
1960 mDownTime = when;
1961 }
1962
1963 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
1964 metaState, buttonState, 0,
1965 mCurrentCookedState.cookedPointerData.pointerProperties,
1966 mCurrentCookedState.cookedPointerData.pointerCoords,
1967 mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits,
1968 downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime);
1969 }
1970 }
1971}
1972
1973void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) {
1974 if (mSentHoverEnter &&
1975 (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() ||
1976 !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) {
1977 int32_t metaState = getContext()->getGlobalMetaState();
1978 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
1979 mLastCookedState.buttonState, 0,
1980 mLastCookedState.cookedPointerData.pointerProperties,
1981 mLastCookedState.cookedPointerData.pointerCoords,
1982 mLastCookedState.cookedPointerData.idToIndex,
1983 mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision,
1984 mOrientedYPrecision, mDownTime);
1985 mSentHoverEnter = false;
1986 }
1987}
1988
1989void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) {
1990 if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() &&
1991 !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) {
1992 int32_t metaState = getContext()->getGlobalMetaState();
1993 if (!mSentHoverEnter) {
1994 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
1995 metaState, mCurrentRawState.buttonState, 0,
1996 mCurrentCookedState.cookedPointerData.pointerProperties,
1997 mCurrentCookedState.cookedPointerData.pointerCoords,
1998 mCurrentCookedState.cookedPointerData.idToIndex,
1999 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2000 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2001 mSentHoverEnter = true;
2002 }
2003
2004 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2005 mCurrentRawState.buttonState, 0,
2006 mCurrentCookedState.cookedPointerData.pointerProperties,
2007 mCurrentCookedState.cookedPointerData.pointerCoords,
2008 mCurrentCookedState.cookedPointerData.idToIndex,
2009 mCurrentCookedState.cookedPointerData.hoveringIdBits, -1,
2010 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2011 }
2012}
2013
2014void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) {
2015 BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState);
2016 const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData);
2017 const int32_t metaState = getContext()->getGlobalMetaState();
2018 int32_t buttonState = mLastCookedState.buttonState;
2019 while (!releasedButtons.isEmpty()) {
2020 int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit());
2021 buttonState &= ~actionButton;
2022 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
2023 actionButton, 0, metaState, buttonState, 0,
2024 mCurrentCookedState.cookedPointerData.pointerProperties,
2025 mCurrentCookedState.cookedPointerData.pointerCoords,
2026 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2027 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2028 }
2029}
2030
2031void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) {
2032 BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState);
2033 const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData);
2034 const int32_t metaState = getContext()->getGlobalMetaState();
2035 int32_t buttonState = mLastCookedState.buttonState;
2036 while (!pressedButtons.isEmpty()) {
2037 int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit());
2038 buttonState |= actionButton;
2039 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton,
2040 0, metaState, buttonState, 0,
2041 mCurrentCookedState.cookedPointerData.pointerProperties,
2042 mCurrentCookedState.cookedPointerData.pointerCoords,
2043 mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1,
2044 mOrientedXPrecision, mOrientedYPrecision, mDownTime);
2045 }
2046}
2047
2048const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) {
2049 if (!cookedPointerData.touchingIdBits.isEmpty()) {
2050 return cookedPointerData.touchingIdBits;
2051 }
2052 return cookedPointerData.hoveringIdBits;
2053}
2054
2055void TouchInputMapper::cookPointerData() {
2056 uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount;
2057
2058 mCurrentCookedState.cookedPointerData.clear();
2059 mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount;
2060 mCurrentCookedState.cookedPointerData.hoveringIdBits =
2061 mCurrentRawState.rawPointerData.hoveringIdBits;
2062 mCurrentCookedState.cookedPointerData.touchingIdBits =
2063 mCurrentRawState.rawPointerData.touchingIdBits;
arthurhung65600042020-04-30 17:55:40 +08002064 mCurrentCookedState.cookedPointerData.canceledIdBits =
2065 mCurrentRawState.rawPointerData.canceledIdBits;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002066
2067 if (mCurrentCookedState.cookedPointerData.pointerCount == 0) {
2068 mCurrentCookedState.buttonState = 0;
2069 } else {
2070 mCurrentCookedState.buttonState = mCurrentRawState.buttonState;
2071 }
2072
2073 // Walk through the the active pointers and map device coordinates onto
2074 // surface coordinates and adjust for display orientation.
2075 for (uint32_t i = 0; i < currentPointerCount; i++) {
2076 const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i];
2077
2078 // Size
2079 float touchMajor, touchMinor, toolMajor, toolMinor, size;
2080 switch (mCalibration.sizeCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002081 case Calibration::SizeCalibration::GEOMETRIC:
2082 case Calibration::SizeCalibration::DIAMETER:
2083 case Calibration::SizeCalibration::BOX:
2084 case Calibration::SizeCalibration::AREA:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002085 if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) {
2086 touchMajor = in.touchMajor;
2087 touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2088 toolMajor = in.toolMajor;
2089 toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2090 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2091 : in.touchMajor;
2092 } else if (mRawPointerAxes.touchMajor.valid) {
2093 toolMajor = touchMajor = in.touchMajor;
2094 toolMinor = touchMinor =
2095 mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor;
2096 size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor)
2097 : in.touchMajor;
2098 } else if (mRawPointerAxes.toolMajor.valid) {
2099 touchMajor = toolMajor = in.toolMajor;
2100 touchMinor = toolMinor =
2101 mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor;
2102 size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor)
2103 : in.toolMajor;
2104 } else {
2105 ALOG_ASSERT(false,
2106 "No touch or tool axes. "
2107 "Size calibration should have been resolved to NONE.");
2108 touchMajor = 0;
2109 touchMinor = 0;
2110 toolMajor = 0;
2111 toolMinor = 0;
2112 size = 0;
2113 }
2114
2115 if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) {
2116 uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count();
2117 if (touchingCount > 1) {
2118 touchMajor /= touchingCount;
2119 touchMinor /= touchingCount;
2120 toolMajor /= touchingCount;
2121 toolMinor /= touchingCount;
2122 size /= touchingCount;
2123 }
2124 }
2125
Michael Wrightaff169e2020-07-02 18:30:52 +01002126 if (mCalibration.sizeCalibration == Calibration::SizeCalibration::GEOMETRIC) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002127 touchMajor *= mGeometricScale;
2128 touchMinor *= mGeometricScale;
2129 toolMajor *= mGeometricScale;
2130 toolMinor *= mGeometricScale;
Michael Wrightaff169e2020-07-02 18:30:52 +01002131 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::AREA) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002132 touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0;
2133 touchMinor = touchMajor;
2134 toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0;
2135 toolMinor = toolMajor;
Michael Wrightaff169e2020-07-02 18:30:52 +01002136 } else if (mCalibration.sizeCalibration == Calibration::SizeCalibration::DIAMETER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002137 touchMinor = touchMajor;
2138 toolMinor = toolMajor;
2139 }
2140
2141 mCalibration.applySizeScaleAndBias(&touchMajor);
2142 mCalibration.applySizeScaleAndBias(&touchMinor);
2143 mCalibration.applySizeScaleAndBias(&toolMajor);
2144 mCalibration.applySizeScaleAndBias(&toolMinor);
2145 size *= mSizeScale;
2146 break;
2147 default:
2148 touchMajor = 0;
2149 touchMinor = 0;
2150 toolMajor = 0;
2151 toolMinor = 0;
2152 size = 0;
2153 break;
2154 }
2155
2156 // Pressure
2157 float pressure;
2158 switch (mCalibration.pressureCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002159 case Calibration::PressureCalibration::PHYSICAL:
2160 case Calibration::PressureCalibration::AMPLITUDE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002161 pressure = in.pressure * mPressureScale;
2162 break;
2163 default:
2164 pressure = in.isHovering ? 0 : 1;
2165 break;
2166 }
2167
2168 // Tilt and Orientation
2169 float tilt;
2170 float orientation;
2171 if (mHaveTilt) {
2172 float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
2173 float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
2174 orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
2175 tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
2176 } else {
2177 tilt = 0;
2178
2179 switch (mCalibration.orientationCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002180 case Calibration::OrientationCalibration::INTERPOLATED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002181 orientation = in.orientation * mOrientationScale;
2182 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002183 case Calibration::OrientationCalibration::VECTOR: {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002184 int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
2185 int32_t c2 = signExtendNybble(in.orientation & 0x0f);
2186 if (c1 != 0 || c2 != 0) {
2187 orientation = atan2f(c1, c2) * 0.5f;
2188 float confidence = hypotf(c1, c2);
2189 float scale = 1.0f + confidence / 16.0f;
2190 touchMajor *= scale;
2191 touchMinor /= scale;
2192 toolMajor *= scale;
2193 toolMinor /= scale;
2194 } else {
2195 orientation = 0;
2196 }
2197 break;
2198 }
2199 default:
2200 orientation = 0;
2201 }
2202 }
2203
2204 // Distance
2205 float distance;
2206 switch (mCalibration.distanceCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002207 case Calibration::DistanceCalibration::SCALED:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002208 distance = in.distance * mDistanceScale;
2209 break;
2210 default:
2211 distance = 0;
2212 }
2213
2214 // Coverage
2215 int32_t rawLeft, rawTop, rawRight, rawBottom;
2216 switch (mCalibration.coverageCalibration) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002217 case Calibration::CoverageCalibration::BOX:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002218 rawLeft = (in.toolMinor & 0xffff0000) >> 16;
2219 rawRight = in.toolMinor & 0x0000ffff;
2220 rawBottom = in.toolMajor & 0x0000ffff;
2221 rawTop = (in.toolMajor & 0xffff0000) >> 16;
2222 break;
2223 default:
2224 rawLeft = rawTop = rawRight = rawBottom = 0;
2225 break;
2226 }
2227
2228 // Adjust X,Y coords for device calibration
2229 // TODO: Adjust coverage coords?
2230 float xTransformed = in.x, yTransformed = in.y;
2231 mAffineTransform.applyTo(xTransformed, yTransformed);
Arthur Hung05de5772019-09-26 18:31:26 +08002232 rotateAndScale(xTransformed, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002233
2234 // Adjust X, Y, and coverage coords for surface orientation.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002235 float left, top, right, bottom;
2236
2237 switch (mSurfaceOrientation) {
2238 case DISPLAY_ORIENTATION_90:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002239 left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2240 right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2241 bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate;
2242 top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate;
2243 orientation -= M_PI_2;
2244 if (mOrientedRanges.haveOrientation &&
2245 orientation < mOrientedRanges.orientation.min) {
2246 orientation +=
2247 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2248 }
2249 break;
2250 case DISPLAY_ORIENTATION_180:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002251 left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
2252 right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
2253 bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate;
2254 top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate;
2255 orientation -= M_PI;
2256 if (mOrientedRanges.haveOrientation &&
2257 orientation < mOrientedRanges.orientation.min) {
2258 orientation +=
2259 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2260 }
2261 break;
2262 case DISPLAY_ORIENTATION_270:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002263 left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
2264 right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
2265 bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2266 top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2267 orientation += M_PI_2;
2268 if (mOrientedRanges.haveOrientation &&
2269 orientation > mOrientedRanges.orientation.max) {
2270 orientation -=
2271 (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min);
2272 }
2273 break;
2274 default:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002275 left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2276 right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate;
2277 bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2278 top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate;
2279 break;
2280 }
2281
2282 // Write output coords.
2283 PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
2284 out.clear();
Arthur Hung4197f6b2020-03-16 15:39:59 +08002285 out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
2286 out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002287 out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
2288 out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
2289 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
2290 out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor);
2291 out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
2292 out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
2293 out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
Michael Wrightaff169e2020-07-02 18:30:52 +01002294 if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002295 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
2296 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
2297 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
2298 out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
2299 } else {
2300 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
2301 out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
2302 }
2303
Chris Yedca44af2020-08-05 15:07:56 -07002304 // Write output relative fields if applicable.
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +00002305 uint32_t id = in.id;
2306 if (mSource == AINPUT_SOURCE_TOUCHPAD &&
2307 mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
2308 const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
2309 float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
2310 float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
2311 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
2312 out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
2313 }
2314
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002315 // Write output properties.
2316 PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i];
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002317 properties.clear();
2318 properties.id = id;
2319 properties.toolType = in.toolType;
2320
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +00002321 // Write id index and mark id as valid.
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002322 mCurrentCookedState.cookedPointerData.idToIndex[id] = i;
Nathaniel R. Lewis50908af2019-08-21 04:46:29 +00002323 mCurrentCookedState.cookedPointerData.validIdBits.markBit(id);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002324 }
2325}
2326
2327void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags,
2328 PointerUsage pointerUsage) {
2329 if (pointerUsage != mPointerUsage) {
2330 abortPointerUsage(when, policyFlags);
2331 mPointerUsage = pointerUsage;
2332 }
2333
2334 switch (mPointerUsage) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002335 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002336 dispatchPointerGestures(when, policyFlags, false /*isTimeout*/);
2337 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002338 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002339 dispatchPointerStylus(when, policyFlags);
2340 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002341 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002342 dispatchPointerMouse(when, policyFlags);
2343 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002344 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002345 break;
2346 }
2347}
2348
2349void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) {
2350 switch (mPointerUsage) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002351 case PointerUsage::GESTURES:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002352 abortPointerGestures(when, policyFlags);
2353 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002354 case PointerUsage::STYLUS:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002355 abortPointerStylus(when, policyFlags);
2356 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002357 case PointerUsage::MOUSE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002358 abortPointerMouse(when, policyFlags);
2359 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002360 case PointerUsage::NONE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002361 break;
2362 }
2363
Michael Wrightaff169e2020-07-02 18:30:52 +01002364 mPointerUsage = PointerUsage::NONE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002365}
2366
2367void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) {
2368 // Update current gesture coordinates.
2369 bool cancelPreviousGesture, finishPreviousGesture;
2370 bool sendEvents =
2371 preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout);
2372 if (!sendEvents) {
2373 return;
2374 }
2375 if (finishPreviousGesture) {
2376 cancelPreviousGesture = false;
2377 }
2378
2379 // Update the pointer presentation and spots.
Michael Wrightaff169e2020-07-02 18:30:52 +01002380 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wright976db0c2020-07-02 00:00:29 +01002381 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002382 if (finishPreviousGesture || cancelPreviousGesture) {
2383 mPointerController->clearSpots();
2384 }
2385
Michael Wrightaff169e2020-07-02 18:30:52 +01002386 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002387 mPointerController->setSpots(mPointerGesture.currentGestureCoords,
2388 mPointerGesture.currentGestureIdToIndex,
2389 mPointerGesture.currentGestureIdBits,
2390 mPointerController->getDisplayId());
2391 }
2392 } else {
Michael Wright976db0c2020-07-02 00:00:29 +01002393 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002394 }
2395
2396 // Show or hide the pointer if needed.
2397 switch (mPointerGesture.currentGestureMode) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002398 case PointerGesture::Mode::NEUTRAL:
2399 case PointerGesture::Mode::QUIET:
2400 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH &&
2401 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002402 // Remind the user of where the pointer is after finishing a gesture with spots.
Michael Wright976db0c2020-07-02 00:00:29 +01002403 mPointerController->unfade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002404 }
2405 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002406 case PointerGesture::Mode::TAP:
2407 case PointerGesture::Mode::TAP_DRAG:
2408 case PointerGesture::Mode::BUTTON_CLICK_OR_DRAG:
2409 case PointerGesture::Mode::HOVER:
2410 case PointerGesture::Mode::PRESS:
2411 case PointerGesture::Mode::SWIPE:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002412 // Unfade the pointer when the current gesture manipulates the
2413 // area directly under the pointer.
Michael Wright976db0c2020-07-02 00:00:29 +01002414 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002415 break;
Michael Wrightaff169e2020-07-02 18:30:52 +01002416 case PointerGesture::Mode::FREEFORM:
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002417 // Fade the pointer when the current gesture manipulates a different
2418 // area and there are spots to guide the user experience.
Michael Wrightaff169e2020-07-02 18:30:52 +01002419 if (mParameters.gestureMode == Parameters::GestureMode::MULTI_TOUCH) {
Michael Wright976db0c2020-07-02 00:00:29 +01002420 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002421 } else {
Michael Wright976db0c2020-07-02 00:00:29 +01002422 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002423 }
2424 break;
2425 }
2426
2427 // Send events!
2428 int32_t metaState = getContext()->getGlobalMetaState();
2429 int32_t buttonState = mCurrentCookedState.buttonState;
2430
2431 // Update last coordinates of pointers that have moved so that we observe the new
2432 // pointer positions at the same time as other pointers that have just gone up.
Michael Wrightaff169e2020-07-02 18:30:52 +01002433 bool down = mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP ||
2434 mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG ||
2435 mPointerGesture.currentGestureMode == PointerGesture::Mode::BUTTON_CLICK_OR_DRAG ||
2436 mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
2437 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE ||
2438 mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002439 bool moveNeeded = false;
2440 if (down && !cancelPreviousGesture && !finishPreviousGesture &&
2441 !mPointerGesture.lastGestureIdBits.isEmpty() &&
2442 !mPointerGesture.currentGestureIdBits.isEmpty()) {
2443 BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2444 mPointerGesture.lastGestureIdBits.value);
2445 moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties,
2446 mPointerGesture.currentGestureCoords,
2447 mPointerGesture.currentGestureIdToIndex,
2448 mPointerGesture.lastGestureProperties,
2449 mPointerGesture.lastGestureCoords,
2450 mPointerGesture.lastGestureIdToIndex, movedGestureIdBits);
2451 if (buttonState != mLastCookedState.buttonState) {
2452 moveNeeded = true;
2453 }
2454 }
2455
2456 // Send motion events for all pointers that went up or were canceled.
2457 BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits);
2458 if (!dispatchedGestureIdBits.isEmpty()) {
2459 if (cancelPreviousGesture) {
2460 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2461 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2462 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2463 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2464 mPointerGesture.downTime);
2465
2466 dispatchedGestureIdBits.clear();
2467 } else {
2468 BitSet32 upGestureIdBits;
2469 if (finishPreviousGesture) {
2470 upGestureIdBits = dispatchedGestureIdBits;
2471 } else {
2472 upGestureIdBits.value =
2473 dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value;
2474 }
2475 while (!upGestureIdBits.isEmpty()) {
2476 uint32_t id = upGestureIdBits.clearFirstMarkedBit();
2477
2478 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0,
2479 metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2480 mPointerGesture.lastGestureProperties,
2481 mPointerGesture.lastGestureCoords,
2482 mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2483 0, mPointerGesture.downTime);
2484
2485 dispatchedGestureIdBits.clearBit(id);
2486 }
2487 }
2488 }
2489
2490 // Send motion events for all pointers that moved.
2491 if (moveNeeded) {
2492 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
2493 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2494 mPointerGesture.currentGestureProperties,
2495 mPointerGesture.currentGestureCoords,
2496 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0,
2497 mPointerGesture.downTime);
2498 }
2499
2500 // Send motion events for all pointers that went down.
2501 if (down) {
2502 BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value &
2503 ~dispatchedGestureIdBits.value);
2504 while (!downGestureIdBits.isEmpty()) {
2505 uint32_t id = downGestureIdBits.clearFirstMarkedBit();
2506 dispatchedGestureIdBits.markBit(id);
2507
2508 if (dispatchedGestureIdBits.count() == 1) {
2509 mPointerGesture.downTime = when;
2510 }
2511
2512 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0,
2513 metaState, buttonState, 0, mPointerGesture.currentGestureProperties,
2514 mPointerGesture.currentGestureCoords,
2515 mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0,
2516 0, mPointerGesture.downTime);
2517 }
2518 }
2519
2520 // Send motion events for hover.
Michael Wrightaff169e2020-07-02 18:30:52 +01002521 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002522 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2523 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2524 mPointerGesture.currentGestureProperties,
2525 mPointerGesture.currentGestureCoords,
2526 mPointerGesture.currentGestureIdToIndex,
2527 mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime);
2528 } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) {
2529 // Synthesize a hover move event after all pointers go up to indicate that
2530 // the pointer is hovering again even if the user is not currently touching
2531 // the touch pad. This ensures that a view will receive a fresh hover enter
2532 // event after a tap.
2533 float x, y;
2534 mPointerController->getPosition(&x, &y);
2535
2536 PointerProperties pointerProperties;
2537 pointerProperties.clear();
2538 pointerProperties.id = 0;
2539 pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2540
2541 PointerCoords pointerCoords;
2542 pointerCoords.clear();
2543 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
2544 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2545
2546 const int32_t displayId = mPointerController->getDisplayId();
Garfield Tanc51d1ba2020-01-28 13:24:04 -08002547 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
2548 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
2549 buttonState, MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
2550 1, &pointerProperties, &pointerCoords, 0, 0, x, y,
2551 mPointerGesture.downTime, /* videoFrames */ {});
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002552 getListener()->notifyMotion(&args);
2553 }
2554
2555 // Update state.
2556 mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode;
2557 if (!down) {
2558 mPointerGesture.lastGestureIdBits.clear();
2559 } else {
2560 mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits;
2561 for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty();) {
2562 uint32_t id = idBits.clearFirstMarkedBit();
2563 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
2564 mPointerGesture.lastGestureProperties[index].copyFrom(
2565 mPointerGesture.currentGestureProperties[index]);
2566 mPointerGesture.lastGestureCoords[index].copyFrom(
2567 mPointerGesture.currentGestureCoords[index]);
2568 mPointerGesture.lastGestureIdToIndex[id] = index;
2569 }
2570 }
2571}
2572
2573void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) {
2574 // Cancel previously dispatches pointers.
2575 if (!mPointerGesture.lastGestureIdBits.isEmpty()) {
2576 int32_t metaState = getContext()->getGlobalMetaState();
2577 int32_t buttonState = mCurrentRawState.buttonState;
2578 dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState,
2579 buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
2580 mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords,
2581 mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1,
2582 0, 0, mPointerGesture.downTime);
2583 }
2584
2585 // Reset the current pointer gesture.
2586 mPointerGesture.reset();
2587 mPointerVelocityControl.reset();
2588
2589 // Remove any current spots.
2590 if (mPointerController != nullptr) {
Michael Wright976db0c2020-07-02 00:00:29 +01002591 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002592 mPointerController->clearSpots();
2593 }
2594}
2595
2596bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
2597 bool* outFinishPreviousGesture, bool isTimeout) {
2598 *outCancelPreviousGesture = false;
2599 *outFinishPreviousGesture = false;
2600
2601 // Handle TAP timeout.
2602 if (isTimeout) {
2603#if DEBUG_GESTURES
2604 ALOGD("Gestures: Processing timeout");
2605#endif
2606
Michael Wrightaff169e2020-07-02 18:30:52 +01002607 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002608 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2609 // The tap/drag timeout has not yet expired.
2610 getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime +
2611 mConfig.pointerGestureTapDragInterval);
2612 } else {
2613 // The tap is finished.
2614#if DEBUG_GESTURES
2615 ALOGD("Gestures: TAP finished");
2616#endif
2617 *outFinishPreviousGesture = true;
2618
2619 mPointerGesture.activeGestureId = -1;
Michael Wrightaff169e2020-07-02 18:30:52 +01002620 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002621 mPointerGesture.currentGestureIdBits.clear();
2622
2623 mPointerVelocityControl.reset();
2624 return true;
2625 }
2626 }
2627
2628 // We did not handle this timeout.
2629 return false;
2630 }
2631
2632 const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count();
2633 const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count();
2634
2635 // Update the velocity tracker.
2636 {
2637 VelocityTracker::Position positions[MAX_POINTERS];
2638 uint32_t count = 0;
2639 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) {
2640 uint32_t id = idBits.clearFirstMarkedBit();
2641 const RawPointerData::Pointer& pointer =
2642 mCurrentRawState.rawPointerData.pointerForId(id);
2643 positions[count].x = pointer.x * mPointerXMovementScale;
2644 positions[count].y = pointer.y * mPointerYMovementScale;
2645 }
2646 mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
2647 positions);
2648 }
2649
2650 // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
2651 // to NEUTRAL, then we should not generate tap event.
Michael Wrightaff169e2020-07-02 18:30:52 +01002652 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER &&
2653 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP &&
2654 mPointerGesture.lastGestureMode != PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002655 mPointerGesture.resetTap();
2656 }
2657
2658 // Pick a new active touch id if needed.
2659 // Choose an arbitrary pointer that just went down, if there is one.
2660 // Otherwise choose an arbitrary remaining pointer.
2661 // This guarantees we always have an active touch id when there is at least one pointer.
2662 // We keep the same active touch id for as long as possible.
2663 int32_t lastActiveTouchId = mPointerGesture.activeTouchId;
2664 int32_t activeTouchId = lastActiveTouchId;
2665 if (activeTouchId < 0) {
2666 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2667 activeTouchId = mPointerGesture.activeTouchId =
2668 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2669 mPointerGesture.firstTouchTime = when;
2670 }
2671 } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) {
2672 if (!mCurrentCookedState.fingerIdBits.isEmpty()) {
2673 activeTouchId = mPointerGesture.activeTouchId =
2674 mCurrentCookedState.fingerIdBits.firstMarkedBit();
2675 } else {
2676 activeTouchId = mPointerGesture.activeTouchId = -1;
2677 }
2678 }
2679
2680 // Determine whether we are in quiet time.
2681 bool isQuietTime = false;
2682 if (activeTouchId < 0) {
2683 mPointerGesture.resetQuietTime();
2684 } else {
2685 isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval;
2686 if (!isQuietTime) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002687 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::PRESS ||
2688 mPointerGesture.lastGestureMode == PointerGesture::Mode::SWIPE ||
2689 mPointerGesture.lastGestureMode == PointerGesture::Mode::FREEFORM) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002690 currentFingerCount < 2) {
2691 // Enter quiet time when exiting swipe or freeform state.
2692 // This is to prevent accidentally entering the hover state and flinging the
2693 // pointer when finishing a swipe and there is still one pointer left onscreen.
2694 isQuietTime = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01002695 } else if (mPointerGesture.lastGestureMode ==
2696 PointerGesture::Mode::BUTTON_CLICK_OR_DRAG &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002697 currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) {
2698 // Enter quiet time when releasing the button and there are still two or more
2699 // fingers down. This may indicate that one finger was used to press the button
2700 // but it has not gone up yet.
2701 isQuietTime = true;
2702 }
2703 if (isQuietTime) {
2704 mPointerGesture.quietTime = when;
2705 }
2706 }
2707 }
2708
2709 // Switch states based on button and pointer state.
2710 if (isQuietTime) {
2711 // Case 1: Quiet time. (QUIET)
2712#if DEBUG_GESTURES
2713 ALOGD("Gestures: QUIET for next %0.3fms",
2714 (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f);
2715#endif
Michael Wrightaff169e2020-07-02 18:30:52 +01002716 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::QUIET) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002717 *outFinishPreviousGesture = true;
2718 }
2719
2720 mPointerGesture.activeGestureId = -1;
Michael Wrightaff169e2020-07-02 18:30:52 +01002721 mPointerGesture.currentGestureMode = PointerGesture::Mode::QUIET;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002722 mPointerGesture.currentGestureIdBits.clear();
2723
2724 mPointerVelocityControl.reset();
2725 } else if (isPointerDown(mCurrentRawState.buttonState)) {
2726 // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG)
2727 // The pointer follows the active touch point.
2728 // Emit DOWN, MOVE, UP events at the pointer location.
2729 //
2730 // Only the active touch matters; other fingers are ignored. This policy helps
2731 // to handle the case where the user places a second finger on the touch pad
2732 // to apply the necessary force to depress an integrated button below the surface.
2733 // We don't want the second finger to be delivered to applications.
2734 //
2735 // For this to work well, we need to make sure to track the pointer that is really
2736 // active. If the user first puts one finger down to click then adds another
2737 // finger to drag then the active pointer should switch to the finger that is
2738 // being dragged.
2739#if DEBUG_GESTURES
2740 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, "
2741 "currentFingerCount=%d",
2742 activeTouchId, currentFingerCount);
2743#endif
2744 // Reset state when just starting.
Michael Wrightaff169e2020-07-02 18:30:52 +01002745 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::BUTTON_CLICK_OR_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002746 *outFinishPreviousGesture = true;
2747 mPointerGesture.activeGestureId = 0;
2748 }
2749
2750 // Switch pointers if needed.
2751 // Find the fastest pointer and follow it.
2752 if (activeTouchId >= 0 && currentFingerCount > 1) {
2753 int32_t bestId = -1;
2754 float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
2755 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
2756 uint32_t id = idBits.clearFirstMarkedBit();
2757 float vx, vy;
2758 if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
2759 float speed = hypotf(vx, vy);
2760 if (speed > bestSpeed) {
2761 bestId = id;
2762 bestSpeed = speed;
2763 }
2764 }
2765 }
2766 if (bestId >= 0 && bestId != activeTouchId) {
2767 mPointerGesture.activeTouchId = activeTouchId = bestId;
2768#if DEBUG_GESTURES
2769 ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, "
2770 "bestId=%d, bestSpeed=%0.3f",
2771 bestId, bestSpeed);
2772#endif
2773 }
2774 }
2775
2776 float deltaX = 0, deltaY = 0;
2777 if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2778 const RawPointerData::Pointer& currentPointer =
2779 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2780 const RawPointerData::Pointer& lastPointer =
2781 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2782 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2783 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2784
2785 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2786 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2787
2788 // Move the pointer using a relative motion.
2789 // When using spots, the click will occur at the position of the anchor
2790 // spot and all other spots will move there.
2791 mPointerController->move(deltaX, deltaY);
2792 } else {
2793 mPointerVelocityControl.reset();
2794 }
2795
2796 float x, y;
2797 mPointerController->getPosition(&x, &y);
2798
Michael Wrightaff169e2020-07-02 18:30:52 +01002799 mPointerGesture.currentGestureMode = PointerGesture::Mode::BUTTON_CLICK_OR_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002800 mPointerGesture.currentGestureIdBits.clear();
2801 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2802 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2803 mPointerGesture.currentGestureProperties[0].clear();
2804 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2805 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2806 mPointerGesture.currentGestureCoords[0].clear();
2807 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2808 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2809 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2810 } else if (currentFingerCount == 0) {
2811 // Case 3. No fingers down and button is not pressed. (NEUTRAL)
Michael Wrightaff169e2020-07-02 18:30:52 +01002812 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::NEUTRAL) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002813 *outFinishPreviousGesture = true;
2814 }
2815
2816 // Watch for taps coming out of HOVER or TAP_DRAG mode.
2817 // Checking for taps after TAP_DRAG allows us to detect double-taps.
2818 bool tapped = false;
Michael Wrightaff169e2020-07-02 18:30:52 +01002819 if ((mPointerGesture.lastGestureMode == PointerGesture::Mode::HOVER ||
2820 mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002821 lastFingerCount == 1) {
2822 if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) {
2823 float x, y;
2824 mPointerController->getPosition(&x, &y);
2825 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2826 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
2827#if DEBUG_GESTURES
2828 ALOGD("Gestures: TAP");
2829#endif
2830
2831 mPointerGesture.tapUpTime = when;
2832 getContext()->requestTimeoutAtTime(when +
2833 mConfig.pointerGestureTapDragInterval);
2834
2835 mPointerGesture.activeGestureId = 0;
Michael Wrightaff169e2020-07-02 18:30:52 +01002836 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002837 mPointerGesture.currentGestureIdBits.clear();
2838 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2839 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2840 mPointerGesture.currentGestureProperties[0].clear();
2841 mPointerGesture.currentGestureProperties[0].id =
2842 mPointerGesture.activeGestureId;
2843 mPointerGesture.currentGestureProperties[0].toolType =
2844 AMOTION_EVENT_TOOL_TYPE_FINGER;
2845 mPointerGesture.currentGestureCoords[0].clear();
2846 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
2847 mPointerGesture.tapX);
2848 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
2849 mPointerGesture.tapY);
2850 mPointerGesture.currentGestureCoords[0]
2851 .setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
2852
2853 tapped = true;
2854 } else {
2855#if DEBUG_GESTURES
2856 ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX,
2857 y - mPointerGesture.tapY);
2858#endif
2859 }
2860 } else {
2861#if DEBUG_GESTURES
2862 if (mPointerGesture.tapDownTime != LLONG_MIN) {
2863 ALOGD("Gestures: Not a TAP, %0.3fms since down",
2864 (when - mPointerGesture.tapDownTime) * 0.000001f);
2865 } else {
2866 ALOGD("Gestures: Not a TAP, incompatible mode transitions");
2867 }
2868#endif
2869 }
2870 }
2871
2872 mPointerVelocityControl.reset();
2873
2874 if (!tapped) {
2875#if DEBUG_GESTURES
2876 ALOGD("Gestures: NEUTRAL");
2877#endif
2878 mPointerGesture.activeGestureId = -1;
Michael Wrightaff169e2020-07-02 18:30:52 +01002879 mPointerGesture.currentGestureMode = PointerGesture::Mode::NEUTRAL;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002880 mPointerGesture.currentGestureIdBits.clear();
2881 }
2882 } else if (currentFingerCount == 1) {
2883 // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG)
2884 // The pointer follows the active touch point.
2885 // When in HOVER, emit HOVER_MOVE events at the pointer location.
2886 // When in TAP_DRAG, emit MOVE events at the pointer location.
2887 ALOG_ASSERT(activeTouchId >= 0);
2888
Michael Wrightaff169e2020-07-02 18:30:52 +01002889 mPointerGesture.currentGestureMode = PointerGesture::Mode::HOVER;
2890 if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002891 if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) {
2892 float x, y;
2893 mPointerController->getPosition(&x, &y);
2894 if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop &&
2895 fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) {
Michael Wrightaff169e2020-07-02 18:30:52 +01002896 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002897 } else {
2898#if DEBUG_GESTURES
2899 ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f",
2900 x - mPointerGesture.tapX, y - mPointerGesture.tapY);
2901#endif
2902 }
2903 } else {
2904#if DEBUG_GESTURES
2905 ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up",
2906 (when - mPointerGesture.tapUpTime) * 0.000001f);
2907#endif
2908 }
Michael Wrightaff169e2020-07-02 18:30:52 +01002909 } else if (mPointerGesture.lastGestureMode == PointerGesture::Mode::TAP_DRAG) {
2910 mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002911 }
2912
2913 float deltaX = 0, deltaY = 0;
2914 if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
2915 const RawPointerData::Pointer& currentPointer =
2916 mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
2917 const RawPointerData::Pointer& lastPointer =
2918 mLastRawState.rawPointerData.pointerForId(activeTouchId);
2919 deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
2920 deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
2921
2922 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
2923 mPointerVelocityControl.move(when, &deltaX, &deltaY);
2924
2925 // Move the pointer using a relative motion.
2926 // When using spots, the hover or drag will occur at the position of the anchor spot.
2927 mPointerController->move(deltaX, deltaY);
2928 } else {
2929 mPointerVelocityControl.reset();
2930 }
2931
2932 bool down;
Michael Wrightaff169e2020-07-02 18:30:52 +01002933 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::TAP_DRAG) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002934#if DEBUG_GESTURES
2935 ALOGD("Gestures: TAP_DRAG");
2936#endif
2937 down = true;
2938 } else {
2939#if DEBUG_GESTURES
2940 ALOGD("Gestures: HOVER");
2941#endif
Michael Wrightaff169e2020-07-02 18:30:52 +01002942 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::HOVER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002943 *outFinishPreviousGesture = true;
2944 }
2945 mPointerGesture.activeGestureId = 0;
2946 down = false;
2947 }
2948
2949 float x, y;
2950 mPointerController->getPosition(&x, &y);
2951
2952 mPointerGesture.currentGestureIdBits.clear();
2953 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
2954 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
2955 mPointerGesture.currentGestureProperties[0].clear();
2956 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
2957 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
2958 mPointerGesture.currentGestureCoords[0].clear();
2959 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x);
2960 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y);
2961 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
2962 down ? 1.0f : 0.0f);
2963
2964 if (lastFingerCount == 0 && currentFingerCount != 0) {
2965 mPointerGesture.resetTap();
2966 mPointerGesture.tapDownTime = when;
2967 mPointerGesture.tapX = x;
2968 mPointerGesture.tapY = y;
2969 }
2970 } else {
2971 // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM)
2972 // We need to provide feedback for each finger that goes down so we cannot wait
2973 // for the fingers to move before deciding what to do.
2974 //
2975 // The ambiguous case is deciding what to do when there are two fingers down but they
2976 // have not moved enough to determine whether they are part of a drag or part of a
2977 // freeform gesture, or just a press or long-press at the pointer location.
2978 //
2979 // When there are two fingers we start with the PRESS hypothesis and we generate a
2980 // down at the pointer location.
2981 //
2982 // When the two fingers move enough or when additional fingers are added, we make
2983 // a decision to transition into SWIPE or FREEFORM mode accordingly.
2984 ALOG_ASSERT(activeTouchId >= 0);
2985
2986 bool settled = when >=
2987 mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval;
Michael Wrightaff169e2020-07-02 18:30:52 +01002988 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::PRESS &&
2989 mPointerGesture.lastGestureMode != PointerGesture::Mode::SWIPE &&
2990 mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07002991 *outFinishPreviousGesture = true;
2992 } else if (!settled && currentFingerCount > lastFingerCount) {
2993 // Additional pointers have gone down but not yet settled.
2994 // Reset the gesture.
2995#if DEBUG_GESTURES
2996 ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, "
2997 "settle time remaining %0.3fms",
2998 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
2999 when) * 0.000001f);
3000#endif
3001 *outCancelPreviousGesture = true;
3002 } else {
3003 // Continue previous gesture.
3004 mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode;
3005 }
3006
3007 if (*outFinishPreviousGesture || *outCancelPreviousGesture) {
Michael Wrightaff169e2020-07-02 18:30:52 +01003008 mPointerGesture.currentGestureMode = PointerGesture::Mode::PRESS;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003009 mPointerGesture.activeGestureId = 0;
3010 mPointerGesture.referenceIdBits.clear();
3011 mPointerVelocityControl.reset();
3012
3013 // Use the centroid and pointer location as the reference points for the gesture.
3014#if DEBUG_GESTURES
3015 ALOGD("Gestures: Using centroid as reference for MULTITOUCH, "
3016 "settle time remaining %0.3fms",
3017 (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval -
3018 when) * 0.000001f);
3019#endif
3020 mCurrentRawState.rawPointerData
3021 .getCentroidOfTouchingPointers(&mPointerGesture.referenceTouchX,
3022 &mPointerGesture.referenceTouchY);
3023 mPointerController->getPosition(&mPointerGesture.referenceGestureX,
3024 &mPointerGesture.referenceGestureY);
3025 }
3026
3027 // Clear the reference deltas for fingers not yet included in the reference calculation.
3028 for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value &
3029 ~mPointerGesture.referenceIdBits.value);
3030 !idBits.isEmpty();) {
3031 uint32_t id = idBits.clearFirstMarkedBit();
3032 mPointerGesture.referenceDeltas[id].dx = 0;
3033 mPointerGesture.referenceDeltas[id].dy = 0;
3034 }
3035 mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits;
3036
3037 // Add delta for all fingers and calculate a common movement delta.
3038 float commonDeltaX = 0, commonDeltaY = 0;
3039 BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value &
3040 mCurrentCookedState.fingerIdBits.value);
3041 for (BitSet32 idBits(commonIdBits); !idBits.isEmpty();) {
3042 bool first = (idBits == commonIdBits);
3043 uint32_t id = idBits.clearFirstMarkedBit();
3044 const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id);
3045 const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id);
3046 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3047 delta.dx += cpd.x - lpd.x;
3048 delta.dy += cpd.y - lpd.y;
3049
3050 if (first) {
3051 commonDeltaX = delta.dx;
3052 commonDeltaY = delta.dy;
3053 } else {
3054 commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx);
3055 commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy);
3056 }
3057 }
3058
3059 // Consider transitions from PRESS to SWIPE or MULTITOUCH.
Michael Wrightaff169e2020-07-02 18:30:52 +01003060 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003061 float dist[MAX_POINTER_ID + 1];
3062 int32_t distOverThreshold = 0;
3063 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3064 uint32_t id = idBits.clearFirstMarkedBit();
3065 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3066 dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale);
3067 if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) {
3068 distOverThreshold += 1;
3069 }
3070 }
3071
3072 // Only transition when at least two pointers have moved further than
3073 // the minimum distance threshold.
3074 if (distOverThreshold >= 2) {
3075 if (currentFingerCount > 2) {
3076 // There are more than two pointers, switch to FREEFORM.
3077#if DEBUG_GESTURES
3078 ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2",
3079 currentFingerCount);
3080#endif
3081 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003082 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003083 } else {
3084 // There are exactly two pointers.
3085 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3086 uint32_t id1 = idBits.clearFirstMarkedBit();
3087 uint32_t id2 = idBits.firstMarkedBit();
3088 const RawPointerData::Pointer& p1 =
3089 mCurrentRawState.rawPointerData.pointerForId(id1);
3090 const RawPointerData::Pointer& p2 =
3091 mCurrentRawState.rawPointerData.pointerForId(id2);
3092 float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y);
3093 if (mutualDistance > mPointerGestureMaxSwipeWidth) {
3094 // There are two pointers but they are too far apart for a SWIPE,
3095 // switch to FREEFORM.
3096#if DEBUG_GESTURES
3097 ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f",
3098 mutualDistance, mPointerGestureMaxSwipeWidth);
3099#endif
3100 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003101 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003102 } else {
3103 // There are two pointers. Wait for both pointers to start moving
3104 // before deciding whether this is a SWIPE or FREEFORM gesture.
3105 float dist1 = dist[id1];
3106 float dist2 = dist[id2];
3107 if (dist1 >= mConfig.pointerGestureMultitouchMinDistance &&
3108 dist2 >= mConfig.pointerGestureMultitouchMinDistance) {
3109 // Calculate the dot product of the displacement vectors.
3110 // When the vectors are oriented in approximately the same direction,
3111 // the angle betweeen them is near zero and the cosine of the angle
3112 // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) *
3113 // mag(v2).
3114 PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1];
3115 PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2];
3116 float dx1 = delta1.dx * mPointerXZoomScale;
3117 float dy1 = delta1.dy * mPointerYZoomScale;
3118 float dx2 = delta2.dx * mPointerXZoomScale;
3119 float dy2 = delta2.dy * mPointerYZoomScale;
3120 float dot = dx1 * dx2 + dy1 * dy2;
3121 float cosine = dot / (dist1 * dist2); // denominator always > 0
3122 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) {
3123 // Pointers are moving in the same direction. Switch to SWIPE.
3124#if DEBUG_GESTURES
3125 ALOGD("Gestures: PRESS transitioned to SWIPE, "
3126 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3127 "cosine %0.3f >= %0.3f",
3128 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3129 mConfig.pointerGestureMultitouchMinDistance, cosine,
3130 mConfig.pointerGestureSwipeTransitionAngleCosine);
3131#endif
Michael Wrightaff169e2020-07-02 18:30:52 +01003132 mPointerGesture.currentGestureMode = PointerGesture::Mode::SWIPE;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003133 } else {
3134 // Pointers are moving in different directions. Switch to FREEFORM.
3135#if DEBUG_GESTURES
3136 ALOGD("Gestures: PRESS transitioned to FREEFORM, "
3137 "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, "
3138 "cosine %0.3f < %0.3f",
3139 dist1, mConfig.pointerGestureMultitouchMinDistance, dist2,
3140 mConfig.pointerGestureMultitouchMinDistance, cosine,
3141 mConfig.pointerGestureSwipeTransitionAngleCosine);
3142#endif
3143 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003144 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003145 }
3146 }
3147 }
3148 }
3149 }
Michael Wrightaff169e2020-07-02 18:30:52 +01003150 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003151 // Switch from SWIPE to FREEFORM if additional pointers go down.
3152 // Cancel previous gesture.
3153 if (currentFingerCount > 2) {
3154#if DEBUG_GESTURES
3155 ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2",
3156 currentFingerCount);
3157#endif
3158 *outCancelPreviousGesture = true;
Michael Wrightaff169e2020-07-02 18:30:52 +01003159 mPointerGesture.currentGestureMode = PointerGesture::Mode::FREEFORM;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003160 }
3161 }
3162
3163 // Move the reference points based on the overall group motion of the fingers
3164 // except in PRESS mode while waiting for a transition to occur.
Michael Wrightaff169e2020-07-02 18:30:52 +01003165 if (mPointerGesture.currentGestureMode != PointerGesture::Mode::PRESS &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003166 (commonDeltaX || commonDeltaY)) {
3167 for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty();) {
3168 uint32_t id = idBits.clearFirstMarkedBit();
3169 PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id];
3170 delta.dx = 0;
3171 delta.dy = 0;
3172 }
3173
3174 mPointerGesture.referenceTouchX += commonDeltaX;
3175 mPointerGesture.referenceTouchY += commonDeltaY;
3176
3177 commonDeltaX *= mPointerXMovementScale;
3178 commonDeltaY *= mPointerYMovementScale;
3179
3180 rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY);
3181 mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY);
3182
3183 mPointerGesture.referenceGestureX += commonDeltaX;
3184 mPointerGesture.referenceGestureY += commonDeltaY;
3185 }
3186
3187 // Report gestures.
Michael Wrightaff169e2020-07-02 18:30:52 +01003188 if (mPointerGesture.currentGestureMode == PointerGesture::Mode::PRESS ||
3189 mPointerGesture.currentGestureMode == PointerGesture::Mode::SWIPE) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003190 // PRESS or SWIPE mode.
3191#if DEBUG_GESTURES
3192 ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d,"
3193 "activeGestureId=%d, currentTouchPointerCount=%d",
3194 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3195#endif
3196 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3197
3198 mPointerGesture.currentGestureIdBits.clear();
3199 mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId);
3200 mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0;
3201 mPointerGesture.currentGestureProperties[0].clear();
3202 mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId;
3203 mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
3204 mPointerGesture.currentGestureCoords[0].clear();
3205 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X,
3206 mPointerGesture.referenceGestureX);
3207 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y,
3208 mPointerGesture.referenceGestureY);
3209 mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f);
Michael Wrightaff169e2020-07-02 18:30:52 +01003210 } else if (mPointerGesture.currentGestureMode == PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003211 // FREEFORM mode.
3212#if DEBUG_GESTURES
3213 ALOGD("Gestures: FREEFORM activeTouchId=%d,"
3214 "activeGestureId=%d, currentTouchPointerCount=%d",
3215 activeTouchId, mPointerGesture.activeGestureId, currentFingerCount);
3216#endif
3217 ALOG_ASSERT(mPointerGesture.activeGestureId >= 0);
3218
3219 mPointerGesture.currentGestureIdBits.clear();
3220
3221 BitSet32 mappedTouchIdBits;
3222 BitSet32 usedGestureIdBits;
Michael Wrightaff169e2020-07-02 18:30:52 +01003223 if (mPointerGesture.lastGestureMode != PointerGesture::Mode::FREEFORM) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003224 // Initially, assign the active gesture id to the active touch point
3225 // if there is one. No other touch id bits are mapped yet.
3226 if (!*outCancelPreviousGesture) {
3227 mappedTouchIdBits.markBit(activeTouchId);
3228 usedGestureIdBits.markBit(mPointerGesture.activeGestureId);
3229 mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] =
3230 mPointerGesture.activeGestureId;
3231 } else {
3232 mPointerGesture.activeGestureId = -1;
3233 }
3234 } else {
3235 // Otherwise, assume we mapped all touches from the previous frame.
3236 // Reuse all mappings that are still applicable.
3237 mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value &
3238 mCurrentCookedState.fingerIdBits.value;
3239 usedGestureIdBits = mPointerGesture.lastGestureIdBits;
3240
3241 // Check whether we need to choose a new active gesture id because the
3242 // current went went up.
3243 for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value &
3244 ~mCurrentCookedState.fingerIdBits.value);
3245 !upTouchIdBits.isEmpty();) {
3246 uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit();
3247 uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId];
3248 if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) {
3249 mPointerGesture.activeGestureId = -1;
3250 break;
3251 }
3252 }
3253 }
3254
3255#if DEBUG_GESTURES
3256 ALOGD("Gestures: FREEFORM follow up "
3257 "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, "
3258 "activeGestureId=%d",
3259 mappedTouchIdBits.value, usedGestureIdBits.value,
3260 mPointerGesture.activeGestureId);
3261#endif
3262
3263 BitSet32 idBits(mCurrentCookedState.fingerIdBits);
3264 for (uint32_t i = 0; i < currentFingerCount; i++) {
3265 uint32_t touchId = idBits.clearFirstMarkedBit();
3266 uint32_t gestureId;
3267 if (!mappedTouchIdBits.hasBit(touchId)) {
3268 gestureId = usedGestureIdBits.markFirstUnmarkedBit();
3269 mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId;
3270#if DEBUG_GESTURES
3271 ALOGD("Gestures: FREEFORM "
3272 "new mapping for touch id %d -> gesture id %d",
3273 touchId, gestureId);
3274#endif
3275 } else {
3276 gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId];
3277#if DEBUG_GESTURES
3278 ALOGD("Gestures: FREEFORM "
3279 "existing mapping for touch id %d -> gesture id %d",
3280 touchId, gestureId);
3281#endif
3282 }
3283 mPointerGesture.currentGestureIdBits.markBit(gestureId);
3284 mPointerGesture.currentGestureIdToIndex[gestureId] = i;
3285
3286 const RawPointerData::Pointer& pointer =
3287 mCurrentRawState.rawPointerData.pointerForId(touchId);
3288 float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale;
3289 float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale;
3290 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3291
3292 mPointerGesture.currentGestureProperties[i].clear();
3293 mPointerGesture.currentGestureProperties[i].id = gestureId;
3294 mPointerGesture.currentGestureProperties[i].toolType =
3295 AMOTION_EVENT_TOOL_TYPE_FINGER;
3296 mPointerGesture.currentGestureCoords[i].clear();
3297 mPointerGesture.currentGestureCoords[i]
3298 .setAxisValue(AMOTION_EVENT_AXIS_X,
3299 mPointerGesture.referenceGestureX + deltaX);
3300 mPointerGesture.currentGestureCoords[i]
3301 .setAxisValue(AMOTION_EVENT_AXIS_Y,
3302 mPointerGesture.referenceGestureY + deltaY);
3303 mPointerGesture.currentGestureCoords[i].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3304 1.0f);
3305 }
3306
3307 if (mPointerGesture.activeGestureId < 0) {
3308 mPointerGesture.activeGestureId =
3309 mPointerGesture.currentGestureIdBits.firstMarkedBit();
3310#if DEBUG_GESTURES
3311 ALOGD("Gestures: FREEFORM new "
3312 "activeGestureId=%d",
3313 mPointerGesture.activeGestureId);
3314#endif
3315 }
3316 }
3317 }
3318
3319 mPointerController->setButtonState(mCurrentRawState.buttonState);
3320
3321#if DEBUG_GESTURES
3322 ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, "
3323 "currentGestureMode=%d, currentGestureIdBits=0x%08x, "
3324 "lastGestureMode=%d, lastGestureIdBits=0x%08x",
3325 toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture),
3326 mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value,
3327 mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value);
3328 for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty();) {
3329 uint32_t id = idBits.clearFirstMarkedBit();
3330 uint32_t index = mPointerGesture.currentGestureIdToIndex[id];
3331 const PointerProperties& properties = mPointerGesture.currentGestureProperties[index];
3332 const PointerCoords& coords = mPointerGesture.currentGestureCoords[index];
3333 ALOGD(" currentGesture[%d]: index=%d, toolType=%d, "
3334 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3335 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3336 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3337 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3338 }
3339 for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty();) {
3340 uint32_t id = idBits.clearFirstMarkedBit();
3341 uint32_t index = mPointerGesture.lastGestureIdToIndex[id];
3342 const PointerProperties& properties = mPointerGesture.lastGestureProperties[index];
3343 const PointerCoords& coords = mPointerGesture.lastGestureCoords[index];
3344 ALOGD(" lastGesture[%d]: index=%d, toolType=%d, "
3345 "x=%0.3f, y=%0.3f, pressure=%0.3f",
3346 id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X),
3347 coords.getAxisValue(AMOTION_EVENT_AXIS_Y),
3348 coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE));
3349 }
3350#endif
3351 return true;
3352}
3353
3354void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) {
3355 mPointerSimple.currentCoords.clear();
3356 mPointerSimple.currentProperties.clear();
3357
3358 bool down, hovering;
3359 if (!mCurrentCookedState.stylusIdBits.isEmpty()) {
3360 uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit();
3361 uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id];
3362 float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX();
3363 float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY();
3364 mPointerController->setPosition(x, y);
3365
3366 hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id);
3367 down = !hovering;
3368
3369 mPointerController->getPosition(&x, &y);
3370 mPointerSimple.currentCoords.copyFrom(
3371 mCurrentCookedState.cookedPointerData.pointerCoords[index]);
3372 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3373 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3374 mPointerSimple.currentProperties.id = 0;
3375 mPointerSimple.currentProperties.toolType =
3376 mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType;
3377 } else {
3378 down = false;
3379 hovering = false;
3380 }
3381
3382 dispatchPointerSimple(when, policyFlags, down, hovering);
3383}
3384
3385void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) {
3386 abortPointerSimple(when, policyFlags);
3387}
3388
3389void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) {
3390 mPointerSimple.currentCoords.clear();
3391 mPointerSimple.currentProperties.clear();
3392
3393 bool down, hovering;
3394 if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
3395 uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
3396 uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3397 float deltaX = 0, deltaY = 0;
3398 if (mLastCookedState.mouseIdBits.hasBit(id)) {
3399 uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id];
3400 deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
3401 mLastRawState.rawPointerData.pointers[lastIndex].x) *
3402 mPointerXMovementScale;
3403 deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
3404 mLastRawState.rawPointerData.pointers[lastIndex].y) *
3405 mPointerYMovementScale;
3406
3407 rotateDelta(mSurfaceOrientation, &deltaX, &deltaY);
3408 mPointerVelocityControl.move(when, &deltaX, &deltaY);
3409
3410 mPointerController->move(deltaX, deltaY);
3411 } else {
3412 mPointerVelocityControl.reset();
3413 }
3414
3415 down = isPointerDown(mCurrentRawState.buttonState);
3416 hovering = !down;
3417
3418 float x, y;
3419 mPointerController->getPosition(&x, &y);
3420 mPointerSimple.currentCoords.copyFrom(
3421 mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
3422 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
3423 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
3424 mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE,
3425 hovering ? 0.0f : 1.0f);
3426 mPointerSimple.currentProperties.id = 0;
3427 mPointerSimple.currentProperties.toolType =
3428 mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType;
3429 } else {
3430 mPointerVelocityControl.reset();
3431
3432 down = false;
3433 hovering = false;
3434 }
3435
3436 dispatchPointerSimple(when, policyFlags, down, hovering);
3437}
3438
3439void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) {
3440 abortPointerSimple(when, policyFlags);
3441
3442 mPointerVelocityControl.reset();
3443}
3444
3445void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down,
3446 bool hovering) {
3447 int32_t metaState = getContext()->getGlobalMetaState();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003448
3449 if (down || hovering) {
Michael Wright976db0c2020-07-02 00:00:29 +01003450 mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003451 mPointerController->clearSpots();
3452 mPointerController->setButtonState(mCurrentRawState.buttonState);
Michael Wright976db0c2020-07-02 00:00:29 +01003453 mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003454 } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) {
Michael Wright976db0c2020-07-02 00:00:29 +01003455 mPointerController->fade(PointerControllerInterface::Transition::GRADUAL);
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003456 }
Garfield Tan9514d782020-11-10 16:37:23 -08003457 int32_t displayId = mPointerController->getDisplayId();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003458
3459 float xCursorPosition;
3460 float yCursorPosition;
3461 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3462
3463 if (mPointerSimple.down && !down) {
3464 mPointerSimple.down = false;
3465
3466 // Send up.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003467 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3468 policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003469 mLastRawState.buttonState, MotionClassification::NONE,
3470 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3471 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3472 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3473 /* videoFrames */ {});
3474 getListener()->notifyMotion(&args);
3475 }
3476
3477 if (mPointerSimple.hovering && !hovering) {
3478 mPointerSimple.hovering = false;
3479
3480 // Send hover exit.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003481 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3482 policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState,
3483 mLastRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003484 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.lastProperties,
3485 &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision,
3486 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3487 /* videoFrames */ {});
3488 getListener()->notifyMotion(&args);
3489 }
3490
3491 if (down) {
3492 if (!mPointerSimple.down) {
3493 mPointerSimple.down = true;
3494 mPointerSimple.downTime = when;
3495
3496 // Send down.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003497 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003498 displayId, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0,
3499 metaState, mCurrentRawState.buttonState,
3500 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3501 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3502 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3503 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3504 getListener()->notifyMotion(&args);
3505 }
3506
3507 // Send move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003508 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3509 policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003510 mCurrentRawState.buttonState, MotionClassification::NONE,
3511 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3512 &mPointerSimple.currentCoords, mOrientedXPrecision,
3513 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3514 mPointerSimple.downTime, /* videoFrames */ {});
3515 getListener()->notifyMotion(&args);
3516 }
3517
3518 if (hovering) {
3519 if (!mPointerSimple.hovering) {
3520 mPointerSimple.hovering = true;
3521
3522 // Send hover enter.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003523 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003524 displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0,
3525 metaState, mCurrentRawState.buttonState,
3526 MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, 1,
3527 &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
3528 mOrientedXPrecision, mOrientedYPrecision, xCursorPosition,
3529 yCursorPosition, mPointerSimple.downTime, /* videoFrames */ {});
3530 getListener()->notifyMotion(&args);
3531 }
3532
3533 // Send hover move.
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003534 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3535 policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
3536 mCurrentRawState.buttonState, MotionClassification::NONE,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003537 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3538 &mPointerSimple.currentCoords, mOrientedXPrecision,
3539 mOrientedYPrecision, xCursorPosition, yCursorPosition,
3540 mPointerSimple.downTime, /* videoFrames */ {});
3541 getListener()->notifyMotion(&args);
3542 }
3543
3544 if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) {
3545 float vscroll = mCurrentRawState.rawVScroll;
3546 float hscroll = mCurrentRawState.rawHScroll;
3547 mWheelYVelocityControl.move(when, nullptr, &vscroll);
3548 mWheelXVelocityControl.move(when, &hscroll, nullptr);
3549
3550 // Send scroll.
3551 PointerCoords pointerCoords;
3552 pointerCoords.copyFrom(mPointerSimple.currentCoords);
3553 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
3554 pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
3555
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003556 NotifyMotionArgs args(getContext()->getNextId(), when, getDeviceId(), mSource, displayId,
3557 policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003558 mCurrentRawState.buttonState, MotionClassification::NONE,
3559 AMOTION_EVENT_EDGE_FLAG_NONE, 1, &mPointerSimple.currentProperties,
3560 &pointerCoords, mOrientedXPrecision, mOrientedYPrecision,
3561 xCursorPosition, yCursorPosition, mPointerSimple.downTime,
3562 /* videoFrames */ {});
3563 getListener()->notifyMotion(&args);
3564 }
3565
3566 // Save state.
3567 if (down || hovering) {
3568 mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords);
3569 mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties);
3570 } else {
3571 mPointerSimple.reset();
3572 }
3573}
3574
3575void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) {
3576 mPointerSimple.currentCoords.clear();
3577 mPointerSimple.currentProperties.clear();
3578
3579 dispatchPointerSimple(when, policyFlags, false, false);
3580}
3581
3582void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source,
3583 int32_t action, int32_t actionButton, int32_t flags,
3584 int32_t metaState, int32_t buttonState, int32_t edgeFlags,
3585 const PointerProperties* properties,
3586 const PointerCoords* coords, const uint32_t* idToIndex,
3587 BitSet32 idBits, int32_t changedId, float xPrecision,
3588 float yPrecision, nsecs_t downTime) {
3589 PointerCoords pointerCoords[MAX_POINTERS];
3590 PointerProperties pointerProperties[MAX_POINTERS];
3591 uint32_t pointerCount = 0;
3592 while (!idBits.isEmpty()) {
3593 uint32_t id = idBits.clearFirstMarkedBit();
3594 uint32_t index = idToIndex[id];
3595 pointerProperties[pointerCount].copyFrom(properties[index]);
3596 pointerCoords[pointerCount].copyFrom(coords[index]);
3597
3598 if (changedId >= 0 && id == uint32_t(changedId)) {
3599 action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
3600 }
3601
3602 pointerCount += 1;
3603 }
3604
3605 ALOG_ASSERT(pointerCount != 0);
3606
3607 if (changedId >= 0 && pointerCount == 1) {
3608 // Replace initial down and final up action.
3609 // We can compare the action without masking off the changed pointer index
3610 // because we know the index is 0.
3611 if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) {
3612 action = AMOTION_EVENT_ACTION_DOWN;
3613 } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) {
arthurhung65600042020-04-30 17:55:40 +08003614 if ((flags & AMOTION_EVENT_FLAG_CANCELED) != 0) {
3615 action = AMOTION_EVENT_ACTION_CANCEL;
3616 } else {
3617 action = AMOTION_EVENT_ACTION_UP;
3618 }
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003619 } else {
3620 // Can't happen.
3621 ALOG_ASSERT(false);
3622 }
3623 }
3624 float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
3625 float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
Michael Wrightaff169e2020-07-02 18:30:52 +01003626 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003627 mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
3628 }
3629 const int32_t displayId = getAssociatedDisplayId().value_or(ADISPLAY_ID_NONE);
3630 const int32_t deviceId = getDeviceId();
Nathaniel R. Lewis26ec2222020-01-10 16:30:54 -08003631 std::vector<TouchVideoFrame> frames = getDeviceContext().getVideoFrames();
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003632 std::for_each(frames.begin(), frames.end(),
3633 [this](TouchVideoFrame& frame) { frame.rotate(this->mSurfaceOrientation); });
Garfield Tanc51d1ba2020-01-28 13:24:04 -08003634 NotifyMotionArgs args(getContext()->getNextId(), when, deviceId, source, displayId, policyFlags,
3635 action, actionButton, flags, metaState, buttonState,
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003636 MotionClassification::NONE, edgeFlags, pointerCount, pointerProperties,
3637 pointerCoords, xPrecision, yPrecision, xCursorPosition, yCursorPosition,
3638 downTime, std::move(frames));
3639 getListener()->notifyMotion(&args);
3640}
3641
3642bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties,
3643 const PointerCoords* inCoords,
3644 const uint32_t* inIdToIndex,
3645 PointerProperties* outProperties,
3646 PointerCoords* outCoords, const uint32_t* outIdToIndex,
3647 BitSet32 idBits) const {
3648 bool changed = false;
3649 while (!idBits.isEmpty()) {
3650 uint32_t id = idBits.clearFirstMarkedBit();
3651 uint32_t inIndex = inIdToIndex[id];
3652 uint32_t outIndex = outIdToIndex[id];
3653
3654 const PointerProperties& curInProperties = inProperties[inIndex];
3655 const PointerCoords& curInCoords = inCoords[inIndex];
3656 PointerProperties& curOutProperties = outProperties[outIndex];
3657 PointerCoords& curOutCoords = outCoords[outIndex];
3658
3659 if (curInProperties != curOutProperties) {
3660 curOutProperties.copyFrom(curInProperties);
3661 changed = true;
3662 }
3663
3664 if (curInCoords != curOutCoords) {
3665 curOutCoords.copyFrom(curInCoords);
3666 changed = true;
3667 }
3668 }
3669 return changed;
3670}
3671
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003672void TouchInputMapper::cancelTouch(nsecs_t when) {
3673 abortPointerUsage(when, 0 /*policyFlags*/);
3674 abortTouches(when, 0 /* policyFlags*/);
3675}
3676
Arthur Hung4197f6b2020-03-16 15:39:59 +08003677// Transform raw coordinate to surface coordinate
Arthur Hung05de5772019-09-26 18:31:26 +08003678void TouchInputMapper::rotateAndScale(float& x, float& y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003679 // Scale to surface coordinate.
3680 const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
3681 const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
3682
arthurhung10052f62020-12-29 20:28:15 +08003683 const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
3684 const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
3685
Arthur Hung4197f6b2020-03-16 15:39:59 +08003686 // Rotate to surface coordinate.
3687 // 0 - no swap and reverse.
3688 // 90 - swap x/y and reverse y.
3689 // 180 - reverse x, y.
3690 // 270 - swap x/y and reverse x.
Arthur Hung05de5772019-09-26 18:31:26 +08003691 switch (mSurfaceOrientation) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003692 case DISPLAY_ORIENTATION_0:
3693 x = xScaled + mXTranslate;
3694 y = yScaled + mYTranslate;
3695 break;
Arthur Hung05de5772019-09-26 18:31:26 +08003696 case DISPLAY_ORIENTATION_90:
arthurhung10052f62020-12-29 20:28:15 +08003697 y = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
Arthur Hung4197f6b2020-03-16 15:39:59 +08003698 x = yScaled + mYTranslate;
Arthur Hung05de5772019-09-26 18:31:26 +08003699 break;
3700 case DISPLAY_ORIENTATION_180:
arthurhung10052f62020-12-29 20:28:15 +08003701 x = xScaledMax - (mRawSurfaceWidth - mSurfaceRight);
3702 y = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003703 break;
3704 case DISPLAY_ORIENTATION_270:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003705 y = xScaled + mXTranslate;
arthurhung10052f62020-12-29 20:28:15 +08003706 x = yScaledMax - (mRawSurfaceHeight - mSurfaceBottom);
Arthur Hung05de5772019-09-26 18:31:26 +08003707 break;
3708 default:
Arthur Hung4197f6b2020-03-16 15:39:59 +08003709 assert(false);
Arthur Hung05de5772019-09-26 18:31:26 +08003710 }
3711}
3712
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003713bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) {
Arthur Hung4197f6b2020-03-16 15:39:59 +08003714 const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
3715 const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
3716
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003717 return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003718 xScaled >= mSurfaceLeft && xScaled <= mSurfaceRight &&
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003719 y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
Arthur Hung4197f6b2020-03-16 15:39:59 +08003720 yScaled >= mSurfaceTop && yScaled <= mSurfaceBottom;
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003721}
3722
3723const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
3724 for (const VirtualKey& virtualKey : mVirtualKeys) {
3725#if DEBUG_VIRTUAL_KEYS
3726 ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, "
3727 "left=%d, top=%d, right=%d, bottom=%d",
3728 x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop,
3729 virtualKey.hitRight, virtualKey.hitBottom);
3730#endif
3731
3732 if (virtualKey.isHit(x, y)) {
3733 return &virtualKey;
3734 }
3735 }
3736
3737 return nullptr;
3738}
3739
3740void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) {
3741 uint32_t currentPointerCount = current->rawPointerData.pointerCount;
3742 uint32_t lastPointerCount = last->rawPointerData.pointerCount;
3743
3744 current->rawPointerData.clearIdBits();
3745
3746 if (currentPointerCount == 0) {
3747 // No pointers to assign.
3748 return;
3749 }
3750
3751 if (lastPointerCount == 0) {
3752 // All pointers are new.
3753 for (uint32_t i = 0; i < currentPointerCount; i++) {
3754 uint32_t id = i;
3755 current->rawPointerData.pointers[i].id = id;
3756 current->rawPointerData.idToIndex[id] = i;
3757 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i));
3758 }
3759 return;
3760 }
3761
3762 if (currentPointerCount == 1 && lastPointerCount == 1 &&
3763 current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) {
3764 // Only one pointer and no change in count so it must have the same id as before.
3765 uint32_t id = last->rawPointerData.pointers[0].id;
3766 current->rawPointerData.pointers[0].id = id;
3767 current->rawPointerData.idToIndex[id] = 0;
3768 current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0));
3769 return;
3770 }
3771
3772 // General case.
3773 // We build a heap of squared euclidean distances between current and last pointers
3774 // associated with the current and last pointer indices. Then, we find the best
3775 // match (by distance) for each current pointer.
3776 // The pointers must have the same tool type but it is possible for them to
3777 // transition from hovering to touching or vice-versa while retaining the same id.
3778 PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS];
3779
3780 uint32_t heapSize = 0;
3781 for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount;
3782 currentPointerIndex++) {
3783 for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount;
3784 lastPointerIndex++) {
3785 const RawPointerData::Pointer& currentPointer =
3786 current->rawPointerData.pointers[currentPointerIndex];
3787 const RawPointerData::Pointer& lastPointer =
3788 last->rawPointerData.pointers[lastPointerIndex];
3789 if (currentPointer.toolType == lastPointer.toolType) {
3790 int64_t deltaX = currentPointer.x - lastPointer.x;
3791 int64_t deltaY = currentPointer.y - lastPointer.y;
3792
3793 uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY);
3794
3795 // Insert new element into the heap (sift up).
3796 heap[heapSize].currentPointerIndex = currentPointerIndex;
3797 heap[heapSize].lastPointerIndex = lastPointerIndex;
3798 heap[heapSize].distance = distance;
3799 heapSize += 1;
3800 }
3801 }
3802 }
3803
3804 // Heapify
3805 for (uint32_t startIndex = heapSize / 2; startIndex != 0;) {
3806 startIndex -= 1;
3807 for (uint32_t parentIndex = startIndex;;) {
3808 uint32_t childIndex = parentIndex * 2 + 1;
3809 if (childIndex >= heapSize) {
3810 break;
3811 }
3812
3813 if (childIndex + 1 < heapSize &&
3814 heap[childIndex + 1].distance < heap[childIndex].distance) {
3815 childIndex += 1;
3816 }
3817
3818 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3819 break;
3820 }
3821
3822 swap(heap[parentIndex], heap[childIndex]);
3823 parentIndex = childIndex;
3824 }
3825 }
3826
3827#if DEBUG_POINTER_ASSIGNMENT
3828 ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize);
3829 for (size_t i = 0; i < heapSize; i++) {
3830 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3831 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3832 }
3833#endif
3834
3835 // Pull matches out by increasing order of distance.
3836 // To avoid reassigning pointers that have already been matched, the loop keeps track
3837 // of which last and current pointers have been matched using the matchedXXXBits variables.
3838 // It also tracks the used pointer id bits.
3839 BitSet32 matchedLastBits(0);
3840 BitSet32 matchedCurrentBits(0);
3841 BitSet32 usedIdBits(0);
3842 bool first = true;
3843 for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) {
3844 while (heapSize > 0) {
3845 if (first) {
3846 // The first time through the loop, we just consume the root element of
3847 // the heap (the one with smallest distance).
3848 first = false;
3849 } else {
3850 // Previous iterations consumed the root element of the heap.
3851 // Pop root element off of the heap (sift down).
3852 heap[0] = heap[heapSize];
3853 for (uint32_t parentIndex = 0;;) {
3854 uint32_t childIndex = parentIndex * 2 + 1;
3855 if (childIndex >= heapSize) {
3856 break;
3857 }
3858
3859 if (childIndex + 1 < heapSize &&
3860 heap[childIndex + 1].distance < heap[childIndex].distance) {
3861 childIndex += 1;
3862 }
3863
3864 if (heap[parentIndex].distance <= heap[childIndex].distance) {
3865 break;
3866 }
3867
3868 swap(heap[parentIndex], heap[childIndex]);
3869 parentIndex = childIndex;
3870 }
3871
3872#if DEBUG_POINTER_ASSIGNMENT
3873 ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize);
3874 for (size_t i = 0; i < heapSize; i++) {
3875 ALOGD(" heap[%zu]: cur=%" PRIu32 ", last=%" PRIu32 ", distance=%" PRIu64, i,
3876 heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance);
3877 }
3878#endif
3879 }
3880
3881 heapSize -= 1;
3882
3883 uint32_t currentPointerIndex = heap[0].currentPointerIndex;
3884 if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched
3885
3886 uint32_t lastPointerIndex = heap[0].lastPointerIndex;
3887 if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched
3888
3889 matchedCurrentBits.markBit(currentPointerIndex);
3890 matchedLastBits.markBit(lastPointerIndex);
3891
3892 uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id;
3893 current->rawPointerData.pointers[currentPointerIndex].id = id;
3894 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3895 current->rawPointerData.markIdBit(id,
3896 current->rawPointerData.isHovering(
3897 currentPointerIndex));
3898 usedIdBits.markBit(id);
3899
3900#if DEBUG_POINTER_ASSIGNMENT
3901 ALOGD("assignPointerIds - matched: cur=%" PRIu32 ", last=%" PRIu32 ", id=%" PRIu32
3902 ", distance=%" PRIu64,
3903 lastPointerIndex, currentPointerIndex, id, heap[0].distance);
3904#endif
3905 break;
3906 }
3907 }
3908
3909 // Assign fresh ids to pointers that were not matched in the process.
3910 for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) {
3911 uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit();
3912 uint32_t id = usedIdBits.markFirstUnmarkedBit();
3913
3914 current->rawPointerData.pointers[currentPointerIndex].id = id;
3915 current->rawPointerData.idToIndex[id] = currentPointerIndex;
3916 current->rawPointerData.markIdBit(id,
3917 current->rawPointerData.isHovering(currentPointerIndex));
3918
3919#if DEBUG_POINTER_ASSIGNMENT
3920 ALOGD("assignPointerIds - assigned: cur=%" PRIu32 ", id=%" PRIu32, currentPointerIndex, id);
3921#endif
3922 }
3923}
3924
3925int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) {
3926 if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) {
3927 return AKEY_STATE_VIRTUAL;
3928 }
3929
3930 for (const VirtualKey& virtualKey : mVirtualKeys) {
3931 if (virtualKey.keyCode == keyCode) {
3932 return AKEY_STATE_UP;
3933 }
3934 }
3935
3936 return AKEY_STATE_UNKNOWN;
3937}
3938
3939int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) {
3940 if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) {
3941 return AKEY_STATE_VIRTUAL;
3942 }
3943
3944 for (const VirtualKey& virtualKey : mVirtualKeys) {
3945 if (virtualKey.scanCode == scanCode) {
3946 return AKEY_STATE_UP;
3947 }
3948 }
3949
3950 return AKEY_STATE_UNKNOWN;
3951}
3952
3953bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes,
3954 const int32_t* keyCodes, uint8_t* outFlags) {
3955 for (const VirtualKey& virtualKey : mVirtualKeys) {
3956 for (size_t i = 0; i < numCodes; i++) {
3957 if (virtualKey.keyCode == keyCodes[i]) {
3958 outFlags[i] = 1;
3959 }
3960 }
3961 }
3962
3963 return true;
3964}
3965
3966std::optional<int32_t> TouchInputMapper::getAssociatedDisplayId() {
3967 if (mParameters.hasAssociatedDisplay) {
Michael Wrightaff169e2020-07-02 18:30:52 +01003968 if (mDeviceMode == DeviceMode::POINTER) {
Prabir Pradhanbaa5c822019-08-30 15:27:05 -07003969 return std::make_optional(mPointerController->getDisplayId());
3970 } else {
3971 return std::make_optional(mViewport.displayId);
3972 }
3973 }
3974 return std::nullopt;
3975}
3976
3977} // namespace android